https://github.com/jonssonyan...html
import threading import time import tkinter.simpledialog from tkinter import END, simpledialog, messagebox import requests 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傳遞的參數 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'] # 獲取發言 text = content['text'] # 獲取發言時間 timeline = content['timeline'] # 記錄發言 msg = timeline + ' ' + nickname + ': ' + text # 判斷對應消息是否存在於日誌,若是和最後一條相同則打印並保存 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(delay, room_id): # 建立bDanmu實例 bDanmu = Danmu(room_id) while True: # 暫停防止cpu佔用太高 time.sleep(delay) # 獲取彈幕 bDanmu.get_danmu() def author(): # 彈出對話框 messagebox.showinfo(title='關於', message='做者:阿壯Jonson\n日期:2021年2月4日\n微信公衆號:科技貓') # tkinter GUI window = tkinter.Tk() window.title('BiliBli彈幕查看工具') window.minsize(300, 500) window.geometry('400x600+250+100') # 菜單欄 menubar = tkinter.Menu(window) # Open放在菜單欄中,就是裝入容器 menubar.add_command(label='關於', command=author) # 建立菜單欄完成後,配置讓菜單欄menubar顯示出來 window.config(menu=menubar) # 滾動條 sc = tkinter.Scrollbar(window) sc.pack(side=tkinter.RIGHT, fill=tkinter.Y) # Listbox控件 listb = tkinter.Listbox(window, yscrollcommand=sc.set) # 將部件放置到主窗口中 listb.pack(side=tkinter.LEFT, fill=tkinter.BOTH, expand=True) # 滾動條動,列表跟着動 sc.config(command=listb.yview) # 獲取字符串(標題,提示,初始值) room_id = simpledialog.askstring(title='請輸入房間號', prompt='請輸入房間號:' , initialvalue='21089733') if room_id is not None: # 建立獲取彈幕線程 try: t = threading.Thread(target=bilibili, args=(0.5, str(room_id),)) t.setDaemon(True) t.start() except: print("Error: 啓動失敗!請檢查房間號是否正確") # 進入循環顯示 window.mainloop()
使用第三方包:pyinstallerpython
pyinstaller -F -w bilibli-danmu.py