針對彈幕的爬取我們如果只需要獲取看到的網頁里面的而數(shù)據(jù),使用selenium就能實現(xiàn),對于直播平臺來說,往往有第三方平臺api讓你獲取數(shù)據(jù)(可以獲取發(fā)彈幕,發(fā)彈幕者的名字禮物等等,這需要客戶端向彈幕服務器發(fā)送登錄請求,心跳信息的發(fā)送等等)只獲取彈幕信息儲存到txt文件中,上代碼,上圖片
代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
|
import time from selenium import webdriver chrome_options = webdriver.chromeoptions() # 使用headless無界面瀏覽器模式 # chrome_options.add_argument('--headless') # chrome_options.add_argument('--disable-gpu') prefs = { "profile.managed_default_content_settings.images" : 2 } chrome_options.add_experimental_option( "prefs" , prefs) browser = webdriver.chrome(chrome_options = chrome_options) url = 'https://www.douyu.com/' def getdanmu(homeid): homehref = url + str (homeid) browser.get(homehref) while 1 : time.sleep( 2 ) try : for i in browser.find_elements_by_xpath( './/div[@class=" danmu-6e95c1"]/div/div' ): if len (i.text) > 0 : try : print (i.text) except : pass savedanmu(i.text) else : continue except : time.sleep( 2 ) for i in browser.find_elements_by_xpath( './/div[@class=" danmu-6e95c1"]/div/div' ): if len (i.text) > 0 : try : print (i.text) except : pass savedanmu(i.text) else : continue def savedanmu(danmu): with open ( 'danmu.txt' , 'a+' , encoding = 'utf-8' )as f: f.write(danmu + '\n' ) if __name__ = = '__main__' : num = input ( '請輸入需要查詢的房間號:' ) getdanmu(num) |
以上就是python基于selenium爬取斗魚彈幕的詳細內容,更多關于python 爬取斗魚彈幕的資料請關注服務器之家其它相關文章!
原文鏈接:https://www.cnblogs.com/Martinaoh/p/14265300.html