Python调用YouTube API v3报错KeyError: 'commentCount'求最优解决方案
问题根因
- 部分YouTube视频设置了评论关闭、评论仅对关注者可见等权限限制,YouTube API v3不会为这类视频返回
commentCount字段,直接硬读取字典键就会触发KeyError - 额外注意:2021年YouTube官方已经公开隐藏了所有视频的踩数统计,
dislikeCount字段目前几乎所有请求都无法获取,后续运行也会触发同类KeyError
最优解决方案
使用Python字典内置的get()方法替代直接按键取值,get()可以在键不存在时返回自定义默认值,无需写冗余的if else判断,同时补充接口异常处理逻辑,避免接口报错导致整个脚本中断。同时还可以优化pandas数据写入逻辑,兼容高版本pandas(append方法在pandas 2.0+已经被正式移除)。
优化后完整代码
# Import libraries import requests import pandas as pd import time # Keys API_KEY = 'xxx' CHANNEL_ID = 'xxx' def get_video_details(video_id): # 收集播放、点赞、踩、评论数 url_video_stats = f'https://www.googleapis.com/youtube/v3/videos?id={video_id}&part=statistics&key={API_KEY}' try: response_video_stats = requests.get(url_video_stats, timeout=10).json() # 先判断接口返回正常且有数据 if not response_video_stats.get('items'): return 0, 0, 0, 0 # 统一取出统计字段,空默认设为空字典 stats = response_video_stats['items'][0].get('statistics', {}) # 用get方法取值,键不存在返回默认值0,可根据需求改成None view_count = stats.get('viewCount', 0) like_count = stats.get('likeCount', 0) dislike_count = stats.get('dislikeCount', 0) comment_count = stats.get('commentCount', 0) return view_count, like_count, dislike_count, comment_count except Exception as e: print(f"获取视频{video_id}数据失败: {str(e)}") return 0, 0, 0, 0 def get_videos(): pageToken = '' # 先用列表存所有数据,最后一次性转DataFrame,性能更高 video_list = [] while True: url = f'https://www.googleapis.com/youtube/v3/search?key={API_KEY}&channelId={CHANNEL_ID}&part=snippet,id&order=date&maxResults=50&{pageToken}' try: response = requests.get(url, timeout=10).json() time.sleep(1) # 接口返回错误直接终止 if 'error' in response: print(f"接口请求失败: {response['error']['message']}") break for video in response['items']: if video['id']['kind'] == "youtube#video": video_id = video['id']['videoId'] video_title = video['snippet']['title'].replace('&','') upload_date = video['snippet']['publishedAt'].split("T")[0] view_count, like_count, dislike_count, comment_count = get_video_details(video_id) video_list.append({ 'video_id': video_id, 'video_title': video_title, 'upload_date': upload_date, 'view_count': view_count, 'like_count': like_count, 'dislike_count': dislike_count, 'comment_count': comment_count }) # 处理翻页 pageToken = f"pageToken={response['nextPageToken']}" if 'nextPageToken' in response else None if not pageToken: break except Exception as e: print(f"请求翻页失败: {str(e)}") break # 一次性转DataFrame return pd.DataFrame(video_list) # 构建DataFrame df2 = get_videos()
额外说明
- 可根据业务需求调整
get()的默认值,比如不需要填0可以设置为None,后续单独做数据清洗 - YouTube search接口单次最多返回50条数据,原代码写maxResults=10000不会生效,优化后修正为符合接口要求的50
- 增加了超时和异常捕获逻辑,遇到网络波动、API配额超限、视频被删除等情况不会直接终止整个脚本
内容的提问来源于stack exchange,提问作者user11278201
相关产品推荐
相关产品推荐

