# Python如何實現爬取某站視頻彈幕并繪制詞云圖
## 前言
在當今互聯網時代,彈幕已成為視頻網站的重要互動形式。通過分析視頻彈幕數據,我們可以了解觀眾的情感傾向、關注焦點等信息。本文將詳細介紹如何使用Python實現從某視頻網站爬取彈幕數據,并通過詞云圖進行可視化分析的全過程。
## 一、技術準備
### 1.1 所需工具和庫
實現本案例需要以下Python庫:
```python
import requests # 網絡請求
import re # 正則表達式
import json # JSON數據處理
from wordcloud import WordCloud # 詞云生成
import jieba # 中文分詞
import matplotlib.pyplot as plt # 數據可視化
import numpy as np # 數值計算
from PIL import Image # 圖像處理
建議使用Python 3.7+版本,并通過pip安裝所需依賴:
pip install requests jieba wordcloud matplotlib pillow numpy
以某視頻網站為例,通過瀏覽器開發者工具分析可知:
https://api.bilibili.com/x/v1/dm/list.so?oid={cid}首先需要獲取目標視頻的cid值:
def get_cid(bvid):
"""通過視頻BV號獲取cid"""
url = f"https://api.bilibili.com/x/web-interface/view?bvid={bvid}"
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36..."
}
response = requests.get(url, headers=headers)
data = json.loads(response.text)
return data['data']['cid']
獲取cid后,可以請求彈幕接口:
def get_danmaku(cid):
"""根據cid獲取彈幕數據"""
url = f"https://api.bilibili.com/x/v1/dm/list.so?oid={cid}"
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36..."
}
response = requests.get(url, headers=headers)
response.encoding = 'utf-8'
# 使用正則提取彈幕內容
pattern = re.compile('<d p=".*?">(.*?)</d>')
danmaku_list = pattern.findall(response.text)
return danmaku_list
原始彈幕數據可能包含特殊字符、空值等,需要進行清洗:
def clean_danmaku(danmaku_list):
"""清洗彈幕數據"""
cleaned = []
for danmaku in danmaku_list:
# 去除前后空格
danmaku = danmaku.strip()
# 過濾空彈幕
if not danmaku:
continue
# 去除特殊字符
danmaku = re.sub(r'[^\w\s]', '', danmaku)
cleaned.append(danmaku)
return cleaned
使用jieba庫進行中文分詞:
def segment_text(text_list):
"""對文本列表進行分詞處理"""
segmented = []
for text in text_list:
words = jieba.cut(text)
segmented.extend(words)
return segmented
創建停用詞表,過濾無意義的詞語:
def load_stopwords(filepath):
"""加載停用詞表"""
with open(filepath, 'r', encoding='utf-8') as f:
stopwords = [line.strip() for line in f]
return set(stopwords)
def filter_stopwords(word_list, stopwords):
"""過濾停用詞"""
return [word for word in word_list if word not in stopwords and len(word) > 1]
統計分詞后的詞頻:
from collections import Counter
def count_word_frequency(word_list):
"""統計詞頻"""
return Counter(word_list)
使用WordCloud生成基礎詞云:
def generate_wordcloud(text, output_path):
"""生成基礎詞云圖"""
wc = WordCloud(
font_path='simhei.ttf', # 中文字體路徑
background_color='white',
width=800,
height=600,
max_words=200
)
wc.generate(text)
wc.to_file(output_path)
使用圖片作為詞云形狀:
def generate_mask_wordcloud(text, mask_path, output_path):
"""生成自定義形狀詞云"""
mask = np.array(Image.open(mask_path))
wc = WordCloud(
font_path='simhei.ttf',
background_color='white',
mask=mask,
max_words=200,
contour_width=3,
contour_color='steelblue'
)
wc.generate(text)
wc.to_file(output_path)
def main():
# 1. 獲取視頻cid
bvid = "BV1GJ411x7h7" # 示例視頻BV號
cid = get_cid(bvid)
# 2. 獲取彈幕數據
danmaku_list = get_danmaku(cid)
# 3. 數據清洗
cleaned_danmaku = clean_danmaku(danmaku_list)
# 4. 分詞處理
segmented_words = segment_text(cleaned_danmaku)
# 5. 加載停用詞表
stopwords = load_stopwords('stopwords.txt')
# 6. 過濾停用詞
filtered_words = filter_stopwords(segmented_words, stopwords)
# 7. 統計詞頻
word_freq = count_word_frequency(filtered_words)
# 8. 生成詞云
text = ' '.join(filtered_words)
generate_wordcloud(text, 'basic_wordcloud.png')
# 9. 生成自定義形狀詞云(可選)
generate_mask_wordcloud(text, 'mask.png', 'mask_wordcloud.png')
if __name__ == '__main__':
main()
生成的詞云圖效果如下:
基礎詞云圖:

自定義形狀詞云圖:

解決方案: - 添加合理的請求頭(User-Agent、Referer等) - 使用代理IP - 設置請求間隔時間
解決方案: - 確保安裝了中文字體 - 在WordCloud中指定正確的中文字體路徑
調整建議: - 嘗試不同的mask圖片 - 調整WordCloud的參數(max_words, max_font_size等) - 預處理圖片確保背景為純色
本文詳細介紹了使用Python爬取視頻彈幕并生成詞云圖的完整流程。通過這個案例,我們不僅可以學習到網絡爬蟲、數據分析和可視化的基本技術,還能深入理解用戶生成內容的價值。讀者可以根據實際需求對代碼進行修改和擴展,開發出更有趣的應用。
完整代碼已上傳至GitHub:項目地址
希望本文對你有所幫助,歡迎交流討論! “`
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。