B站评论删除 API 逆向分析:3 个关键参数 (oid, type, csrf) 获取与实战
B站评论删除API逆向工程实战:关键参数解析与自动化操作指南
1. 理解B站评论删除机制的核心逻辑
在视频平台内容管理中,评论删除功能涉及复杂的权限验证和数据交互流程。B站的评论删除API采用了一套基于Web安全标准的防护机制,主要依赖三个关键参数实现身份验证和操作授权:
- oid:目标内容的对象标识符,相当于数据库中的主键
- type:内容类型分类代码,决定API路由路径
- csrf:跨站请求伪造令牌,用于防止未授权操作
通过Chrome开发者工具分析网络请求时,可以看到典型的删除请求结构如下:
POST /x/v2/reply/del HTTP/1.1 Host: api.bilibili.com Content-Type: application/x-www-form-urlencoded oid=123456789&type=1&rpid=987654321&csrf=abcdef0123456789注意:实际操作中必须使用已登录状态的Cookie,否则csrf验证会失败。每个用户的csrf令牌具有唯一性和时效性。
2. 关键参数获取方法论
2.1 oid参数的定位技巧
oid(Object ID)根据内容类型不同,其获取方式存在差异:
| 内容类型 | oid来源 | 示例值范围 |
|---|---|---|
| 视频 | 视频AV号或BV号转换 | 8-10位数字 |
| 专栏文章 | 文章cv编号 | 7-9位数字 |
| 动态 | 动态did | 11位数字 |
| 音频 | 音频au编号 | 6-8位数字 |
在网页端可通过以下JavaScript代码快速获取当前页面的oid:
// 视频页面 window.__INITIAL_STATE__.aid // 动态页面 window.__INITIAL_STATE__.dynamic.id2.2 type参数枚举表
type参数采用固定数值对应不同内容类型:
| 数值 | 内容类型 | 典型应用场景 |
|---|---|---|
| 1 | 视频 | 主站视频评论 |
| 11 | 专栏 | 文章评论区 |
| 17 | 动态 | 用户动态互动 |
| 14 | 音频 | 音乐区内容评论 |
| 12 | 课程 | 课堂类内容 |
2.3 csrf令牌的三种获取方式
Cookie提取法:
document.cookie.match(/bili_jct=([^;]+)/)[1]页面元素提取:
# 使用BeautifulSoup解析 soup.find('meta', {'name': 'csrf_token'})['content']API响应提取:
curl -s 'https://api.bilibili.com/x/web-interface/nav' | jq '.data.token'
3. 实战操作:构建自动化删除工具
3.1 浏览器开发者工具操作流程
- 打开目标内容页面(视频/动态/专栏)
- 右键点击评论 → 选择"检查"
- 切换到Network面板 → 勾选Preserve log
- 执行删除操作 → 观察新增的POST请求
- 复制请求中的Form Data参数
3.2 Python自动化脚本示例
import requests def delete_comment(oid, rpid, type_, csrf, cookie): url = "https://api.bilibili.com/x/v2/reply/del" headers = { "User-Agent": "Mozilla/5.0", "Cookie": cookie } data = { "oid": oid, "type": type_, "rpid": rpid, "csrf": csrf } response = requests.post(url, headers=headers, data=data) return response.json() # 示例调用 result = delete_comment( oid="12345678", rpid="56789012", type_=1, csrf="abcdef123456", cookie="SESSDATA=xxxxxx; bili_jct=yyyyyy" ) print(result)提示:实际使用时需要替换为真实的参数值和Cookie信息,建议通过环境变量管理敏感数据。
4. 安全机制与反爬策略应对
B站的API防护体系主要包含以下安全层:
请求频率限制:
- 单IP每分钟不超过60次请求
- 相同操作间隔需大于5秒
签名验证:
- 关键参数需要MD5哈希校验
- 时间戳参与签名计算
行为验证:
- 异常操作触发Geetest验证
- 账号行为模式分析
应对建议:
- 添加随机延迟(3-10秒)
- 使用真实浏览器UA头
- 避免集中批量操作
5. 高级应用:评论管理系统设计
对于需要管理大量内容的UP主,可以构建基于Flask的Web管理界面:
from flask import Flask, request import sqlite3 app = Flask(__name__) @app.route('/manage', methods=['POST']) def manage_comments(): conn = sqlite3.connect('comments.db') c = conn.cursor() # 获取待处理评论列表 c.execute("SELECT * FROM pending_comments WHERE status=0") comments = c.fetchall() for comment in comments: result = delete_comment( oid=comment[1], rpid=comment[2], type_=comment[3], csrf=request.form['csrf'], cookie=request.form['cookie'] ) if result['code'] == 0: c.execute("UPDATE pending_comments SET status=1 WHERE id=?", (comment[0],)) conn.commit() conn.close() return {'status': 'success'}配套数据库schema设计:
CREATE TABLE pending_comments ( id INTEGER PRIMARY KEY, oid INTEGER NOT NULL, rpid INTEGER NOT NULL, type INTEGER NOT NULL, content TEXT, post_time DATETIME, status INTEGER DEFAULT 0 );6. 异常处理与日志记录
完善的错误处理机制应包含以下组件:
重试机制:
from tenacity import retry, stop_after_attempt, wait_exponential @retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=4, max=10)) def safe_delete(oid, rpid, type_, csrf, cookie): return delete_comment(oid, rpid, type_, csrf, cookie)日志记录:
import logging logging.basicConfig( filename='comment_mod.log', format='%(asctime)s - %(levelname)s - %(message)s', level=logging.INFO ) try: result = safe_delete(...) logging.info(f"Deleted rpid:{rpid} oid:{oid}") except Exception as e: logging.error(f"Failed to delete {rpid}: {str(e)}")结果验证:
- 检查返回JSON中的code字段
- 验证ttl值是否为1
- 确认message内容
7. 浏览器扩展开发方案
通过Chrome扩展可以更便捷地获取页面参数:
// manifest.json { "manifest_version": 3, "name": "B站评论管理助手", "version": "1.0", "permissions": ["cookies", "https://*.bilibili.com/*"], "action": { "default_popup": "popup.html" }, "content_scripts": [{ "matches": ["https://*.bilibili.com/*"], "js": ["content.js"] }] } // content.js chrome.runtime.onMessage.addListener((request, sender, sendResponse) => { if (request.action === "getCommentInfo") { const oid = window.__INITIAL_STATE__.aid; const csrf = document.cookie.match(/bili_jct=([^;]+)/)[1]; sendResponse({oid, csrf}); } });扩展功能模块设计:
- 当前页面参数自动获取
- 评论列表可视化展示
- 批量选择删除操作
- 操作历史记录查询
