调用YouTube API获取指定频道视频返回非预期数据如何排查?
问题根源排查
maxResults参数取值违规:YouTube Data API v3的search接口maxResults有效值范围为0~50,你填写的200会被API自动忽略,默认返回50条结果,同时可能引发参数解析异常- pageToken拼接逻辑错误:你直接将pageToken拼在maxResults参数后,没有添加
&pageToken=前缀,即便是空值也会导致URL格式异常,API无法正确识别channelId参数 - 频道ID填写错误:你填写的ID并非James Charles的官方频道ID,正确ID为
UCucot-Zp428OwkyRm2I7v2Q,错误ID指向无关频道自然返回异常内容 - 可选优化:建议添加
type=video参数,限定仅返回视频内容,避免播放列表、直播预告等无关资源被返回
修正后代码
youtubevar.py文件内容
# These variables above are in the youtubevar.py files where I keep my variables apikey = 'xxxxxxxxxxxxxx' # 修正后的James Charles官方频道ID channelid = 'UCucot-Zp428OwkyRm2I7v2Q' pageToken = ''
主文件内容
import requests import pandas as pd import seaborn as sns %pylab inline from youtubevar import * # 改用params参数传参,避免手动拼接URL出错 params = { "key": apikey, "channelId": channelid, "part": "snippet,id", "order": "date", "maxResults": 50, "pageToken": pageToken, "type": "video" } url = 'https://www.googleapis.com/youtube/v3/search' # 调用API response = requests.get(url, params=params).json() # 查看返回结果 print(response)
修正后返回的结果中所有条目的snippet.channelId字段会和你传入的频道ID一致,不会再出现无关频道的内容。
内容的提问来源于stack exchange,提问作者Herc01
相关产品推荐
相关产品推荐

