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

YouTube Playlist API无法返回频道全部视频,如何获取所有视频?

解决YouTube API无法获取频道全部视频的问题

问题根源

你遇到的限制是YouTube Data API v3的官方规则:playlistItems.list接口针对频道的上传播放列表(即你使用的UU...开头的列表),最多只能返回最近的20000条视频,这就是你仅能获取约20k条内容的核心原因。

解决方案

要获取频道的全部公开视频,需改用search.list接口,通过指定频道ID并搜索该频道下的所有视频来绕过这个限制。以下是具体实现:

修改后的代码示例

api_key = "你的Google YouTube API V3密钥"
from googleapiclient.discovery import build
import time

youtube = build('youtube', 'v3', developerKey=api_key)

def get_all_channel_videos(channel_id):
    videos = []
    next_page_token = None
    processed_video_ids = set()  # 去重,避免重复获取相同视频
    while True:
        try:
            res = youtube.search().list(
                channelId=channel_id,
                part='id,snippet',
                maxResults=50,
                order='date',  # 按上传时间排序,确保遍历所有视频
                pageToken=next_page_token,
                type='video',  # 仅返回视频类型结果
            ).execute()
            
            # 提取视频信息并去重
            for item in res['items']:
                video_id = item['id']['videoId']
                if video_id not in processed_video_ids:
                    processed_video_ids.add(video_id)
                    videos.append({
                        'videoId': video_id,
                        'title': item['snippet']['title']
                    })
            
            next_page_token = res.get('nextPageToken')
            if not next_page_token:
                break
            
            # 增加延迟,避免触发API频率限制
            time.sleep(1)
            
        except Exception as e:
            print(f"请求出错: {str(e)}")
            # 遇到错误时延迟重试
            time.sleep(5)
            continue
    
    return videos

# 替换为你的频道ID(UC开头,原UU列表对应的频道ID是把第二个U换成C)
channel_id = "UC..."
videos = get_all_channel_videos(channel_id)

# 写入文件
with open("video.txt", "w") as myfile:
    for video in videos:
        myfile.write(f"{video['videoId']} => {video['title']}\n")

print(f"Total video count => {len(videos)}")

关键注意事项

  • 配额消耗:search.list每次调用消耗100单位API配额,默认每日配额为10000,因此每天最多可获取5000条视频(10000/100*50)。若要获取291k条视频,需分约59天完成,或前往Google Cloud Console申请提高API配额。
  • 去重处理:processed_video_ids集合用于避免API返回重复结果导致数据冗余。
  • 频率限制:time.sleep()是为了避免触发API的频率限制,防止请求被拒绝。
  • 私有视频:API无法获取频道的私有视频,仅能获取公开可见的内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 07:05:02