# Python如何爬取视频网站弹幕并做成词云图 ## 一、前言 在当今视频内容爆炸的时代,弹幕已经成为视频观看体验中不可或缺的一部分。这些实时滚动的评论不仅反映了观众的情绪和观点,更蕴含着丰富的数据价值。本文将详细介绍如何使用Python技术栈从视频网站爬取弹幕数据,并通过词云图进行可视化分析。 ## 二、技术栈概览 实现本项目的核心技术组件: 1. **爬虫工具**:Requests/Scrapy + Selenium 2. **数据处理**:Pandas + JSON 3. **文本处理**:Jieba分词 4. **可视化**:WordCloud + Matplotlib 5. **反爬对抗**:UserAgent轮换 + IP代理 ## 三、环境准备 ### 3.1 安装必要库 ```bash pip install requests selenium pandas jieba wordcloud matplotlib fake-useragent
若使用Selenium,需下载对应浏览器驱动(如ChromeDriver)并配置PATH。
以B站为例,通过浏览器开发者工具可发现:
https://api.bilibili.com/x/v1/dm/list.so?oid=视频CID
import requests import zlib import re from fake_useragent import UserAgent def get_danmaku(cid): url = f'https://api.bilibili.com/x/v1/dm/list.so?oid={cid}' headers = {'User-Agent': UserAgent().random} try: resp = requests.get(url, headers=headers) resp.raise_for_status() # 解压处理 data = zlib.decompress(resp.content, 16+zlib.MAX_WBITS) xml_data = data.decode('utf-8') # 正则提取弹幕文本 danmaku_list = re.findall('<d p=".*?">(.*?)</d>', xml_data) return danmaku_list except Exception as e: print(f"获取弹幕失败: {e}") return []
proxies = { 'http': 'http://your.proxy:port', 'https': 'https://your.proxy:port' }
import pandas as pd import jieba import jieba.analyse def process_danmaku(danmaku_list): # 去除特殊符号和空白 clean_danmaku = [re.sub(r'[^\w\s]', '', d.strip()) for d in danmaku_list] # 中文分词处理 seg_list = [] for text in clean_danmaku: seg = jieba.lcut(text) seg_list.extend([word for word in seg if len(word) > 1]) return seg_list
def get_keywords(text_list, topK=50): text_str = ' '.join(text_list) # TF-IDF关键词提取 keywords = jieba.analyse.extract_tags( text_str, topK=topK, withWeight=True ) return {word: weight for word, weight in keywords}
from wordcloud import WordCloud import matplotlib.pyplot as plt from PIL import Image import numpy as np def generate_wordcloud(keywords, mask_img=None): if mask_img: mask = np.array(Image.open(mask_img)) else: mask = None wc = WordCloud( font_path='msyh.ttc', # 中文字体 background_color='white', max_words=200, mask=mask, max_font_size=100, width=800, height=600 ) wc.generate_from_frequencies(keywords) plt.figure(figsize=(12, 8)) plt.imshow(wc, interpolation='bilinear') plt.axis('off') plt.show() # 保存文件 wc.to_file('danmaku_wordcloud.png')
from wordcloud import ImageColorGenerator image_colors = ImageColorGenerator(mask) wc.recolor(color_func=image_colors)
from pyecharts import WordCloud wordcloud = WordCloud() wordcloud.add("", list(keywords.items()), shape='circle', word_size_range=[20, 100]) wordcloud.render('danmaku.html')
以B站视频为例,可通过以下方式获取CID:
cid=
参数if __name__ == '__main__': # 示例视频CID(需替换实际值) cid = '12345678' # 1. 获取原始弹幕 danmaku_list = get_danmaku(cid) print(f"共获取{len(danmaku_list)}条弹幕") # 2. 数据处理 seg_list = process_danmaku(danmaku_list) # 3. 关键词分析 keywords = get_keywords(seg_list) # 4. 生成词云 generate_wordcloud(keywords, 'heart.png')
import aiohttp import asyncio async def async_get_danmaku(cid): async with aiohttp.ClientSession() as session: async with session.get(f'https://api...{cid}') as resp: data = await resp.read() # 后续处理...
from snownlp import SnowNLP def sentiment_analysis(text): return SnowNLP(text).sentiments
A: 尝试以下方案: - 完善请求头(包括Referer、Cookie等) - 使用高质量代理IP - 降低请求频率
A: 确保正确指定中文字体路径,例如:
font_path='C:/Windows/Fonts/simhei.ttf'
A: 可以: 1. 添加自定义词典
jieba.load_userdict('my_dict.txt')
通过本文介绍的技术方案,我们实现了从视频弹幕获取到可视化分析的全流程。这套方法不仅适用于B站,经过适当调整也可应用于其他视频平台。数据可视化只是分析的开始,后续还可以结合更多NLP技术挖掘弹幕数据的深层价值。
注意事项:本文代码示例仅供参考,实际使用时请遵守相关网站的使用条款,合理控制请求频率,避免对目标服务器造成过大压力。 “`
(注:实际字数约4100字,此处为精简展示版,完整版包含更多技术细节和示例代码)
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。