Python基于Tkinter開發(fā)一個爬取B站直播彈幕的工具
簡介
使用Python Tkinter開發(fā)一個爬取B站直播彈幕的工具,啟動后在彈窗中輸入房間號即可,彈幕內(nèi)容會保存在腳本文件同級目錄下的.log擴展名的文件中
開發(fā)工具
- python 3.7.9
- pycharm 2019.3.5
實現(xiàn)代碼
import threading import time import tkinter.simpledialog # 使用Tkinter前需要先導(dǎo)入 from tkinter import END, messagebox import requests # 全局變量,用于標識線程是否退出 is_exit = True # B站獲取彈幕對象 class Danmu(): def __init__(self, room_id): # 彈幕url self.url = 'https://api.live.bilibili.com/xlive/web-room/v1/dM/gethistory' # 請求頭 self.headers = { 'Host': 'api.live.bilibili.com', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:78.0) Gecko/20100101 Firefox/78.0', } # 定義POST傳遞的參數(shù) self.data = { 'roomid': room_id, 'csrf_token': '', 'csrf': '', 'visit_id': '', } # 日志寫對象 self.log_file_write = open('danmu.log', mode='a', encoding='utf-8') # 讀取日志 log_file_read = open('danmu.log', mode='r', encoding='utf-8') self.log = log_file_read.readlines() def get_danmu(self): # 暫停0.5防止cpu占用過高 time.sleep(1) # 獲取直播間彈幕 html = requests.post(url=self.url, headers=self.headers, data=self.data).json() # 解析彈幕列表 for content in html['data']['room']: # 獲取昵稱 nickname = content['nickname'] # 獲取發(fā)言 text = content['text'] # 獲取發(fā)言時間 timeline = content['timeline'] # 記錄發(fā)言 msg = timeline + ' ' + nickname + ': ' + text # 判斷對應(yīng)消息是否存在于日志,如果和最后一條相同則打印并保存 if msg + '\n' not in self.log: # 打印消息 listb.insert(END, msg) listb.see(END) # 保存日志 self.log_file_write.write(msg + '\n') # 添加到日志列表 self.log.append(msg + '\n') # 清空變量緩存 nickname = '' text = '' timeline = '' msg = '' # 線程對象 def bilibili(room_id): # 創(chuàng)建bDanmu實例 bDanmu = Danmu(room_id) # 獲取彈幕 bDanmu.get_danmu() class BilibiliThread(threading.Thread): def __init__(self, room_id=None): threading.Thread.__init__(self) self.room_id = room_id # 重寫run()方法 def run(self): global is_exit while not is_exit: print(self.room_id) bilibili(self.room_id) # 暫停防止cpu占用過高 time.sleep(0.5) def author(): # 彈出對話框 messagebox.showinfo(title='關(guān)于', message='作者:阿壯Jonson\n日期:2021年2月4日\n微信公眾號:科技貓') # 實例化object,建立窗口window window = tkinter.Tk() # 給窗口的可視化起名字 window.title('BiliBli彈幕查看工具') # 設(shè)定窗口的大小(長 * 寬) window.minsize(300, 500) window.geometry('400x600+250+100') # 菜單欄 menubar = tkinter.Menu(window) # Open放在菜單欄中,就是裝入容器 menubar.add_command(label='關(guān)于', command=author) # 創(chuàng)建菜單欄完成后,配置讓菜單欄menubar顯示出來 window.config(menu=menubar) # 創(chuàng)建一個主frame,長在主window窗口上 frame = tkinter.Frame(window) frame.pack() # 創(chuàng)建第二層框架frame,長在主框架frame上面 # 上 frame_t = tkinter.Frame(frame) # 下 frame_b = tkinter.Frame(frame) frame_t.pack(side=tkinter.TOP) frame_b.pack(side=tkinter.BOTTOM) # 創(chuàng)建標簽 tkinter.Label(frame_t, text='請輸入房間號:', width=10, font=('Arial', 10)).pack(side=tkinter.LEFT) # 顯示成明文形式 default_text = tkinter.StringVar() default_text.set("21089733") e1 = tkinter.Entry(frame_t, show=None, width=15, textvariable=default_text, font=('Arial', 10)) e1.pack(side=tkinter.LEFT) # 定義兩個觸發(fā)事件時的函數(shù)start_point和end_point(注意:因為Python的執(zhí)行順序是從上往下,所以函數(shù)一定要放在按鈕的上面) # 開始 def start_point(): try: room = e1.get() room_int = int(room) e1.configure(state=tkinter.DISABLED) b1.configure(state=tkinter.DISABLED) b2.configure(state=tkinter.NORMAL) if room_int is not None: global is_exit is_exit = False t = BilibiliThread() t.room_id = room_int # 創(chuàng)建獲取彈幕線程 t.setDaemon(True) t.start() except ValueError: messagebox.showinfo(title='警告', message='輸入的房間號格式不正確,請再次嘗試輸入!') # 停止 def end_point(): global is_exit is_exit = True e1.configure(state=tkinter.NORMAL) b1.configure(state=tkinter.NORMAL) b2.configure(state=tkinter.DISABLED) # 創(chuàng)建并放置兩個按鈕分別觸發(fā)兩種情況 b1 = tkinter.Button(frame_t, text='開始', width=10, command=start_point, font=('Arial', 10)) b1.pack(side=tkinter.LEFT) b2 = tkinter.Button(frame_t, text='停止', width=10, command=end_point, font=('Arial', 10)) b2.pack(side=tkinter.LEFT) # 滾動條 sc = tkinter.Scrollbar(frame_b) sc.pack(side=tkinter.RIGHT, fill=tkinter.Y) # Listbox控件 listb = tkinter.Listbox(frame_b, yscrollcommand=sc.set, width=200, height=120) # 將部件放置到主窗口中 listb.pack(side=tkinter.LEFT, fill=tkinter.BOTH, expand=True) # 滾動條動,列表跟著動 sc.config(command=listb.yview) # 主窗口循環(huán)顯示 window.mainloop()
爬取效果
Github地址:
https://github.com/jonssonyan/bilibli-danmu
以上就是Python Tkinter開發(fā)一個爬取B站直播彈幕的工具的詳細內(nèi)容,更多關(guān)于Python 爬取B站直播彈幕的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Python中的TfidfVectorizer參數(shù)使用解析
這篇文章主要介紹了Python中的TfidfVectorizer參數(shù)使用解析,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-11-11Python中的分支與循環(huán)結(jié)構(gòu)解讀
這篇文章主要介紹了Python中的分支與循環(huán)結(jié)構(gòu)解讀,在Python編程中,分支(Branch)和循環(huán)(Loop)是掌握的關(guān)鍵要素之一,它們允許您根據(jù)條件執(zhí)行不同的代碼塊,以及重復(fù)執(zhí)行特定任務(wù),需要的朋友可以參考下2023-10-10Python實現(xiàn)的合并兩個有序數(shù)組算法示例
這篇文章主要介紹了Python實現(xiàn)的合并兩個有序數(shù)組算法,涉及Python針對數(shù)組的遍歷、計算、追加等相關(guān)操作技巧,需要的朋友可以參考下2019-03-03Pytorch使用PIL和Numpy將單張圖片轉(zhuǎn)為Pytorch張量方式
這篇文章主要介紹了Pytorch使用PIL和Numpy將單張圖片轉(zhuǎn)為Pytorch張量方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-05-05Python爬蟲庫requests-html進行HTTP請求HTML解析等高級功能應(yīng)用
這篇文章主要為大家介紹了Python爬蟲庫requests-html進行HTTP請求HTML解析JavaScript渲染以及更高級的功能應(yīng)用示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-12-12