知識點
- 爬蟲基本流程
- 正則
- requests >>> pip install requests
- jieba >>> pip install jieba
- imageio >>> pip install imageio
- wordcloud >>> pip install wordcloud
開發環境
- add path 勾選 其他可以默認安裝
- Python越新的版本 代表的一些模塊不太兼容
- Python 3.6 / 3.8 >>> python解釋器(環境)
- Pycharm >>> python編輯器
代碼實現過程步驟:
- 導入模塊
- 發送請求 對於 彈幕url發送請求
- 解析數據 提取我們想要彈幕內容
- 保存數據 爬取彈幕 可以保存csv文件 保存txt
爬蟲代碼
導入模塊
import requests import re
發送請求
url = 'https://api.bilibili.com/x/v1/dm/list.so?oid=392402545' headers = { 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36' } response = requests.get(url=url, headers=headers) response.encoding = response.apparent_encoding
解析數據
# re 正則表達式 html_data = re.findall('<d p=".*?">(.*?)</d>', response.text) print(html_data)
保存數據
for index in html_data: with open('彈幕1.txt', mode='a', encoding='utf-8') as f: f.write(index) f.write('\n') print(index)

對於本篇文章有疑問的同學可以加【資料白嫖、解答交流群:1039649593】
詞雲代碼
import jieba # 分詞模塊 pip install jiebe import wordcloud # 詞雲模塊 pip install wordcloud import imageio # 自定義詞雲樣式 pip install imageio py = imageio.imread('python.png') # 詞雲 統計哪些詞語出現次數比較多, 次數出現的越多的話 字體顯示越大 f = open('彈幕1.txt', encoding='utf-8') txt = f.read() # print(txt) txt_list = jieba.lcut(txt) string = ' '.join(txt_list) print(string) wc = wordcloud.WordCloud( width=500, # 寬度 height=500, # 高度 background_color='white', # 背景顏色 font_path='msyh.ttc', # 字體文件 mask=py, stopwords={'了', '這個', '啊', '我', '的'}, # 停用詞 # contour_width=5, # contour_color='red' ) wc.generate(string) wc.to_file('output3.png')
