尧图网站设计 尧图网站设计YAOTU DESIGN
ARTICLE DETAIL

资讯详情

深耕网站设计与一线实操的经验洞察。

深度解析bilibili-api评论获取功能:从403错误到高效解决方案

深度解析bilibili-api评论获取功能:从403错误到高效解决方案 深度解析bilibili-api评论获取功能从403错误到高效解决方案【免费下载链接】bilibili-api哔哩哔哩常用API调用。支持视频、番剧、用户、频道、音频等功能。原仓库地址https://github.com/MoyuScript/bilibili-api项目地址: https://gitcode.com/gh_mirrors/bi/bilibili-apiB站作为中国最大的视频分享平台之一其评论系统承载着丰富的用户互动数据。bilibili-api库为开发者提供了便捷的评论获取接口但在实际应用中常遇到403错误和分页问题。本文将深入分析这些问题的根源并提供实用的解决方案。评论获取接口演变从传统到现代bilibili-api提供了两种主要的评论获取方式它们各有特点接口类型方法名分页方式稳定性推荐度传统接口get_comments页码分页已过时★★☆☆☆新版接口get_comments_lazy游标分页高稳定★★★★★传统接口的问题与局限传统get_comments接口采用简单的页码分页方式但随着B站反爬机制的升级这种方式已不再可靠# 传统接口示例已不推荐 from bilibili_api import comment, sync async def get_video_comments_old(): comments [] page 1 while True: c await comment.get_comments( 418788911, comment.CommentResourceType.VIDEO, page ) # ...处理评论这种方法的主要问题在于403错误频发B站服务器会拒绝频繁的页码请求认证要求高第二页及以后需要完整的Credential认证分页不稳定容易因网络波动导致数据重复或丢失新版懒加载接口的优势get_comments_lazy接口采用游标分页机制大大提升了稳定性# 新版接口推荐 from bilibili_api import comment, sync, Credential async def get_comments_efficiently(): credential Credential(sessdata你的sessdata) # 可选但推荐 offset all_comments [] while True: result await comment.get_comments_lazy( oid418788911, type_comment.CommentResourceType.VIDEO, offsetoffset, credentialcredential ) # 处理当前页评论 for reply in result.get(replies, []): print(f{reply[member][uname]}: {reply[content][message]}) all_comments.append(reply) # 获取下一页偏移量 next_offset result[cursor][pagination_reply][next_offset] if not next_offset or result[cursor][is_end]: break offset next_offset return all_comments图1B站投票相关HTML代码结构展示了平台互动元素的复杂性常见问题排查与解决方案问题1403 Forbidden错误症状请求返回403状态码无法获取评论数据。根本原因B站反爬机制升级传统接口已被限制缺少必要的认证信息请求频率过高触发保护机制解决方案切换到新版接口立即使用get_comments_lazy替代get_comments添加认证信息即使不是必需也建议提供Credential控制请求频率添加适当的延迟import asyncio import time async def get_comments_with_retry(oid, type_, credentialNone, max_retries3): 带重试机制的评论获取 for attempt in range(max_retries): try: result await comment.get_comments_lazy( oidoid, type_type_, credentialcredential ) return result except Exception as e: if attempt max_retries - 1: await asyncio.sleep(2 ** attempt) # 指数退避 else: raise问题2pagination_str参数编码错误症状offset参数处理不当导致请求失败。解决方案# 正确的offset处理方式 def prepare_offset(offset_str): 正确处理offset参数 if not offset_str: return {offset:} return f{{offset:{offset_str}}} # 在循环中正确使用 offset while True: result await comment.get_comments_lazy( oidoid, type_type_, offsetoffset, credentialcredential ) # 获取下一次的offset offset result[cursor][pagination_reply][next_offset] if not offset or result[cursor][is_end]: break问题3重试次数达到最大限制症状出现重试达到最大次数错误提示。排查步骤检查网络连接确保网络稳定验证参数正确性确认oid和type_参数正确更新认证信息检查Credential是否过期降低请求频率添加请求间隔最佳实践指南1. 认证信息管理虽然get_comments_lazy的第一页请求不需要认证但为了稳定性和完整数据获取建议始终提供Credentialfrom bilibili_api import Credential # 创建认证对象 credential Credential( sessdata你的sessdata, bili_jct你的bili_jct, buvid3你的buvid3 ) # 验证认证信息有效性 async def validate_credential(credential): try: # 尝试获取用户信息验证认证 from bilibili_api import user user_info await user.get_self_info(credential) return True except: return False2. 错误处理与重试机制构建健壮的评论获取系统需要完善的错误处理import logging from typing import Optional, Dict, Any class CommentFetcher: def __init__(self, credential: Optional[Credential] None): self.credential credential self.logger logging.getLogger(__name__) async def fetch_all_comments(self, oid: int, type_: comment.CommentResourceType, max_pages: int 100) - List[Dict[str, Any]]: 获取所有评论带错误处理 all_comments [] offset page_count 0 while page_count max_pages: try: result await self._fetch_page(oid, type_, offset) if not result or replies not in result: break # 处理评论数据 for reply in result[replies]: processed self._process_comment(reply) all_comments.append(processed) # 检查是否结束 if result[cursor][is_end]: break # 获取下一页offset offset result[cursor][pagination_reply][next_offset] if not offset: break page_count 1 await asyncio.sleep(0.5) # 控制请求频率 except Exception as e: self.logger.error(f获取评论失败: {e}) await asyncio.sleep(2) continue return all_comments async def _fetch_page(self, oid: int, type_: comment.CommentResourceType, offset: str, retries: int 3) - Optional[Dict]: 单页获取带重试 for i in range(retries): try: return await comment.get_comments_lazy( oidoid, type_type_, offsetoffset, credentialself.credential ) except Exception as e: if i retries - 1: await asyncio.sleep(2 ** i) # 指数退避 else: raise return None def _process_comment(self, reply: Dict) - Dict: 处理单条评论数据 return { id: reply[rpid], user: reply[member][uname], message: reply[content][message], like_count: reply[like], time: reply[ctime], reply_count: reply.get(rcount, 0) }3. 资源类型支持bilibili-api支持多种资源类型的评论获取from bilibili_api.comment import CommentResourceType # 视频评论 video_comments await comment.get_comments_lazy( oid418788911, type_CommentResourceType.VIDEO ) # 专栏文章评论 article_comments await comment.get_comments_lazy( oid9762979, type_CommentResourceType.ARTICLE ) # 动态评论 dynamic_comments await comment.get_comments_lazy( oid116859542, type_CommentResourceType.DYNAMIC ) # 音频评论 audio_comments await comment.get_comments_lazy( oid13998, type_CommentResourceType.AUDIO )性能优化建议1. 并发控制当需要获取多个视频的评论时合理控制并发数import asyncio from typing import List async def fetch_multiple_videos_comments(video_ids: List[int], credential: Optional[Credential] None, max_concurrent: int 5): 并发获取多个视频评论 semaphore asyncio.Semaphore(max_concurrent) async def fetch_one(video_id: int): async with semaphore: return await get_comments_lazy( oidvideo_id, type_CommentResourceType.VIDEO, credentialcredential ) tasks [fetch_one(vid) for vid in video_ids] return await asyncio.gather(*tasks, return_exceptionsTrue)2. 数据存储优化对于大量评论数据的存储建议采用分批处理和压缩import json import gzip from datetime import datetime def save_comments_to_file(comments: List[Dict], filename: str): 保存评论数据到压缩JSON文件 timestamp datetime.now().strftime(%Y%m%d_%H%M%S) full_filename f{filename}_{timestamp}.json.gz data { metadata: { total_comments: len(comments), fetch_time: timestamp, source: bilibili-api }, comments: comments } with gzip.open(full_filename, wt, encodingutf-8) as f: json.dump(data, f, ensure_asciiFalse, indent2) return full_filename总结bilibili-api的评论获取功能虽然强大但在实际使用中需要注意接口版本选择、认证信息管理和错误处理。通过采用get_comments_lazy接口、合理控制请求频率、完善错误处理机制开发者可以稳定高效地获取B站评论数据。关键要点回顾优先使用新版接口get_comments_lazy比传统接口更稳定可靠合理使用认证信息即使非必需也建议提供Credential以提高成功率完善的错误处理添加重试机制和异常捕获控制请求频率避免触发B站的反爬机制关注项目更新及时更新bilibili-api版本以获取最新功能修复通过遵循本文的最佳实践开发者可以构建稳定、高效的B站评论数据采集系统为内容分析、用户行为研究等应用提供可靠的数据支持。【免费下载链接】bilibili-api哔哩哔哩常用API调用。支持视频、番剧、用户、频道、音频等功能。原仓库地址https://github.com/MoyuScript/bilibili-api项目地址: https://gitcode.com/gh_mirrors/bi/bilibili-api创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表