fix(kb-bilibili-content): Improve browser headers and cookie support

- Add complete browser headers for better API compatibility
- Read BILIBILI_COOKIE from environment variable
- Add debug print statements for troubleshooting
This commit is contained in:
OpenClaw Agent
2026-02-10 14:29:35 +08:00
parent 4cdbc825ce
commit 26accdd726
+23 -7
View File
@@ -26,18 +26,29 @@ from typing import Optional, Dict, Any, List
class BilibiliContent:
"""B站内容获取器"""
# 完整的浏览器请求头
BROWSER_HEADERS = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8',
'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
'Accept-Encoding': 'gzip, deflate, br',
'Connection': 'keep-alive',
'Upgrade-Insecure-Requests': '1',
'Sec-Fetch-Dest': 'document',
'Sec-Fetch-Mode': 'navigate',
'Sec-Fetch-Site': 'none',
'Sec-Fetch-User': '?1',
'Cache-Control': 'max-age=0',
}
def __init__(self, output_dir: str = "./output", cookie: str = None):
self.output_dir = Path(output_dir)
self.output_dir.mkdir(parents=True, exist_ok=True)
self.cookie = cookie
def _get_headers(self) -> Dict[str, str]:
headers = {
'Referer': 'https://www.bilibili.com/',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
'Accept': 'application/json',
'Accept-Language': 'zh-CN,zh;q=0.9',
}
"""获取请求头(包含Cookie)"""
headers = self.BROWSER_HEADERS.copy()
if self.cookie:
headers['Cookie'] = self.cookie
return headers
@@ -143,9 +154,12 @@ class BilibiliContent:
try:
async with aiohttp.ClientSession(headers=self._get_headers()) as session:
print(f"获取专栏: {cvid}")
async with session.get("https://api.bilibili.com/x/article/viewinfo", params={'id': cvid}) as resp:
data = await resp.json()
print(f"状态: {data.get('code')} - {data.get('message')}")
if data.get('code') != 0:
result["message"] = f"获取失败: {data.get('message')}"
return result
@@ -174,7 +188,9 @@ async def main():
parser.add_argument('--json', action='store_true', help='JSON输出')
args = parser.parse_args()
downloader = BilibiliContent(output_dir=args.output)
cookie = os.environ.get('BILIBILI_COOKIE')
downloader = BilibiliContent(output_dir=args.output, cookie=cookie)
if args.type == 'video':
result = await downloader.download_video(args.id, quality=args.quality)