YouTube API非英文评论报错及播放列表条目数量异常问题求助
问题1:非英文评论视频触发403错误(误报评论关闭)
原因
你遇到的403错误提示评论关闭,但实际视频未关闭评论,大概率是视频存在年龄/地区限制,或是API返回的错误信息存在误判。另外当前代码的错误处理过于笼统,无法区分真实的评论关闭和其他权限限制场景。
解决方案
修改fetch_comments函数,增强错误解析以区分具体错误类型,同时优化评论内容处理避免编码问题:
from googleapiclient.discovery import build from googleapiclient.errors import HttpError import json youtube = build('youtube', 'v3', developerKey='My_API Key') def fetch_comments(video_id): try: request = youtube.commentThreads().list( part="snippet,replies", videoId=video_id, maxResults=10, order="relevance", textFormat="plainText" # 明确指定文本格式,规避编码兼容问题 ).execute() for item in request['items']: comment = item['snippet']['topLevelComment']['snippet']['textOriginal'] print(comment) # Python3原生支持Unicode,无需额外编码转换 except HttpError as e: # 解析详细错误信息,精准定位问题 error_details = json.loads(e.content) error_reason = error_details['error']['errors'][0]['reason'] if error_reason == "commentsDisabled": print(f"视频 {video_id} 确实关闭了评论") elif error_reason == "videoNotFound": print(f"视频 {video_id} 不存在") elif error_reason == "forbidden": print(f"无权限访问视频 {video_id} 的评论(可能是年龄/地区限制)") else: print(f"获取评论失败: {e.resp.status} {e.resp.reason}")
问题2:播放列表返回条目数量不足设定的max_results
原因
YouTube API的playlistItems.list接口采用分页返回结果,当前代码仅获取了第一页数据;同时你读取文件中的number参数后未传入get_playlist_items函数,导致始终使用默认值15,且未处理分页补全数据的逻辑。
解决方案
修改get_playlist_items函数添加分页逻辑,同时传入文件中读取的number作为目标获取数量:
def get_playlist_items(youtube, playlist_id, max_results=15): video_urls = [] next_page_token = None # 循环获取分页数据,直到达到目标数量或无更多页面 while len(video_urls) < max_results: # 单页最多返回50条,取剩余需要的数量和50的最小值 page_size = min(max_results - len(video_urls), 50) request = youtube.playlistItems().list( part='snippet', playlistId=playlist_id, maxResults=page_size, pageToken=next_page_token ) response = request.execute() # 提取当前页的视频URL for item in response.get('items', []): video_id = item['snippet']['resourceId']['videoId'] video_url = f"https://www.youtube.com/watch?v={video_id}" video_urls.append(video_url) next_page_token = response.get('nextPageToken') if not next_page_token: break # 无更多页面,退出循环 return video_urls[:max_results] # 确保返回数量不超过设定值
同时修改主循环中的函数调用,传入读取到的number参数:
f = open("playlist.txt", 'r') lines = f.readlines() for line in lines: line = line.strip() URL = line.split(', ')[0] number = int(line.split(', ')[1]) playlist_id = URL.split('=')[-1] # 传入文件中指定的number作为目标获取数量 video_urls = get_playlist_items(youtube, playlist_id, max_results=number) print(f"获取到{len(video_urls)}条视频") for url in video_urls : print(url) video_id = url.split('=')[-1] fetch_comments(video_id) f.close()
内容的提问来源于stack exchange,提问作者0xf2f759
相关产品推荐
相关产品推荐

