【Python爬蟲】15行代碼教你爬B站視頻彈幕,詞雲圖展示數據(附源碼)


知識點

  1. 爬蟲基本流程
  2. 正則
  3. requests >>> pip install requests
  4. jieba >>> pip install jieba
  5. imageio >>> pip install imageio
  6. wordcloud >>> pip install wordcloud

開發環境

  • add path 勾選 其他可以默認安裝
  • Python越新的版本 代表的一些模塊不太兼容
  • Python 3.6 / 3.8 >>> python解釋器(環境)
  • Pycharm >>> python編輯器

代碼實現過程步驟:

  1. 導入模塊
  2. 發送請求 對於 彈幕url發送請求
  3. 解析數據 提取我們想要彈幕內容
  4. 保存數據 爬取彈幕 可以保存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')

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM