深度模拟用户行为:用Playwright爬取B站弹幕与评论数据
💡 引言:B站数据为何如此“难爬”?
B站(Bilibili)作为国内最受欢迎的视频弹幕网站之一,页面采用大量JavaScript渲染,数据接口绑定复杂的登录验证和加密参数,直接使用 requests
等传统方式已难以满足爬虫需求。
如果你想:
-
获取某视频的弹幕内容(实时滚动弹幕)
-
获取评论区的真实用户评论(分页加载 + 登录校验)
-
绕过浏览器检测机制,模拟真实用户行为访问网页
那么,Playwright 是一个极具威力的自动化武器,远胜Selenium,性能更好,支持无头模式,适配Chromium/Firefox/WebKit。深度模拟用户行为:用Playwright爬取B站弹幕与评论数据
一、准备工作:环境安装与配置
1. 安装Playwright
pip install playwright
playwright install
二、目标与思路
我们将实现以下目标:
功能 | 实现方式 |
---|---|
打开B站视频页面 | Playwright模拟用户访问 |
自动登录(可选) | 账号Cookie复用 |
提取视频弹幕 | 调用 |
提取视频评论 | 模拟滚动评论区 + 接口抓取 |
三、实战步骤详解
1. 获取 cid
(弹幕接口的关键参数)
每个视频的 cid
可以通过接口获取:
import requestsdef get_cid(bvid):api = f'https://api.bilibili.com/x/player/pagelist?bvid={bvid}'resp = requests.get(api)json_data = resp.json()return json_data['data'][0]['cid']
2. 获取弹幕内容(XML)
from xml.etree import ElementTreedef get_danmaku(cid):url = f'https://comment.bilibili.com/{cid}.xml'response = requests.get(url)response.encoding = 'utf-8'root = ElementTree.fromstring(response.text)print("弹幕列表:")for d in root.findall('d'):print(d.text)
3. 获取评论内容(Playwright模拟浏览器)
import asyncio
from playwright.async_api import async_playwright
import jsonasync def fetch_comments(bvid):async with async_playwright() as p:browser = await p.chromium.launch(headless=False) # 设为True为无头模式context = await browser.new_context()page = await context.new_page()url = f"https://www.bilibili.com/video/{bvid}"await page.goto(url)await page.wait_for_timeout(5000) # 等待页面加载await page.mouse.wheel(0, 5000) # 滚动到底部加载评论# 拦截评论请求数据包comments = []async def handle_response(response):if "main?oid" in response.url and response.status == 200:try:json_data = await response.json()replies = json_data['data']['replies']for r in replies:comments.append(r['content']['message'])except:passpage.on("response", handle_response)await page.wait_for_timeout(5000) # 等待评论加载print("评论内容:")for c in comments:print(" -", c)await browser.close()# 示例调用
asyncio.run(fetch_comments("BV1Kb4y1D7hq"))
四、可选:Cookie登录绕过账号验证
B站部分评论或视频需登录后才能访问,推荐使用已登录账号的Cookie导入方式:
ookies = [ {"name": "SESSDATA", "value": "你的值", "domain": ".bilibili.com", "path": "/"},
# 可添加其他字段如 bili_jct、buvid3 等 ] # Playwright上下文中注入Cookie await context.add_cookies(cookies)
五、进阶建议:模拟人类行为
为了防止Playwright被检测为自动化工具,可引入以下策略:
- 1.加载图片/视频内容,减少“无头痕迹”
- 2.随机鼠标移动、滚动时间间隔
- 3.使用
playwright-stealth
插件
- 4.使用
undetected_chromedriver
替代方案
六、爬虫工具推荐
爬虫在线转换: 爬虫工具箱 - 在线爬虫与数据处理工具