You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python调用YouTube Data API批量获取多频道videoId遇空结果排查

问题排查与解决方案

问题原因

YouTube Data API 的 search.list 接口中,channelId 参数仅支持传入单个频道ID字符串,不接受逗号分隔的多个ID。你用逗号拼接多个ID传入时,API会将这个拼接后的字符串当作一个完整的频道ID去查询,而这个ID对应的频道不存在,因此返回空结果。

解决方案

方案一:循环遍历单个频道ID调用API

逐个对每个频道ID发起请求,收集所有视频ID:

channel_ids = ['UCiT9RITQ9PW6BhXK0y2jaeg',
               'UC7cs8q-gJRlGwj4A8OmCmXg',
               'UC2UXDak6o7rBm23k3Vv5dww']

all_video_ids = []

for channel_id in channel_ids:
    request = youtube.search().list(
        part='id',
        channelId=channel_id,
        type='video',
        order='date',
        maxResults=10
    )
    response = request.execute()
    # 提取当前频道的视频ID
    video_ids = [item['id']['videoId'] for item in response.get('items', [])]
    all_video_ids.extend(video_ids)

print(all_video_ids)

方案二:通过上传播放列表获取全量视频ID(推荐)

如果需要获取频道的所有视频(而非仅maxResults指定的数量),建议先通过channels.list获取频道的上传播放列表ID,再用playlistItems.list遍历播放列表获取完整视频列表,这种方法更高效且配额消耗更低:

channel_ids = ['UCiT9RITQ9PW6BhXK0y2jaeg',
               'UC7cs8q-gJRlGwj4A8OmCmXg',
               'UC2UXDak6o7rBm23k3Vv5dww']

all_video_ids = []

for channel_id in channel_ids:
    # 获取频道的上传播放列表ID
    channel_req = youtube.channels().list(
        part='contentDetails',
        id=channel_id
    )
    channel_res = channel_req.execute()
    uploads_playlist_id = channel_res['items'][0]['contentDetails']['relatedPlaylists']['uploads']
    
    # 分页遍历播放列表,获取所有视频
    next_page_token = None
    while True:
        playlist_req = youtube.playlistItems().list(
            part='contentDetails',
            playlistId=uploads_playlist_id,
            maxResults=50,
            pageToken=next_page_token
        )
        playlist_res = playlist_req.execute()
        video_ids = [item['contentDetails']['videoId'] for item in playlist_res.get('items', [])]
        all_video_ids.extend(video_ids)
        
        next_page_token = playlist_res.get('nextPageToken')
        if not next_page_token:
            break

print(all_video_ids)

注意事项

  • API有配额限制:search.list每次请求消耗100单位配额,channels.list和playlistItems.list每次各消耗1单位,默认每日配额为10000单位,批量请求时需注意控制用量。
  • 若处理大量频道,建议在请求间添加短暂延迟(如time.sleep(1)),避免触发速率限制。

内容的提问来源于stack exchange,提问作者arpit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 04:26:03