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

使用YouTube API v3 subscriptions.list仅获取少量订阅频道的问题

问题

近期我在使用YouTube API v3,尝试获取个人账号下的所有订阅频道,于是采用了官方提供的Python示例代码:

# -*- coding: utf-8 -*-

# Sample Python code for youtube.subscriptions.list
# See instructions for running these code samples locally:
# https://developers.google.com/explorer-help/code-samples#python

import os

import google_auth_oauthlib.flow
import googleapiclient.discovery
import googleapiclient.errors

scopes = ["https://www.googleapis.com/auth/youtube.readonly"]

def main():
    # Disable OAuthlib's HTTPS verification when running locally.
    # *DO NOT* leave this option enabled in production.
    os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"

    api_service_name = "youtube"
    api_version = "v3"
    client_secrets_file = "YOUR_CLIENT_SECRET_FILE.json"

    # Get credentials and create an API client
    flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(
        client_secrets_file, scopes)
    credentials = flow.run_console()
    youtube = googleapiclient.discovery.build(
        api_service_name, api_version, credentials=credentials)

    request = youtube.subscriptions().list(
        part="snippet,contentDetails",
        mine=True
    )
    response = request.execute()

    print(response)

if __name__ == "__main__":
    main()

代码可正常运行,但仅返回5-6个频道的信息,而我实际订阅了200多个频道,且已确认未超出API配额,请问这是什么原因?

解决方法
  • YouTube API v3的列表接口默认采用分页机制,单次请求最多返回50条结果(默认仅返回5条左右),如果订阅数超过单次返回上限,必须通过nextPageToken循环请求后续页面才能拿到全部数据。
  • 原示例代码只执行了一次请求,自然只能获取第一页的少量数据,加入分页逻辑即可解决问题。

修改后的完整代码:

# -*- coding: utf-8 -*-

import os

import google_auth_oauthlib.flow
import googleapiclient.discovery
import googleapiclient.errors

scopes = ["https://www.googleapis.com/auth/youtube.readonly"]

def main():
    os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"

    api_service_name = "youtube"
    api_version = "v3"
    client_secrets_file = "YOUR_CLIENT_SECRET_FILE.json"

    flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(
        client_secrets_file, scopes)
    credentials = flow.run_console()
    youtube = googleapiclient.discovery.build(
        api_service_name, api_version, credentials=credentials)

    all_subscriptions = []
    next_page_token = None

    while True:
        request = youtube.subscriptions().list(
            part="snippet,contentDetails",
            mine=True,
            maxResults=50,  # 设置单次请求最大返回数,上限为50
            pageToken=next_page_token
        )
        response = request.execute()
        all_subscriptions.extend(response.get("items", []))
        
        next_page_token = response.get("nextPageToken")
        if not next_page_token:
            break  # 没有下一页时退出循环

    print(f"共获取到 {len(all_subscriptions)} 个订阅频道")
    # 可按需处理所有订阅数据,例如打印每个频道名称
    for sub in all_subscriptions:
        print(sub["snippet"]["title"])

if __name__ == "__main__":
    main()
  • 核心修改点:
    • 添加maxResults=50参数,每次请求拉取最多50条数据,提升遍历效率
    • 用循环结合nextPageToken遍历所有分页,直到没有下一页为止
    • 用列表all_subscriptions统一收集所有页面的订阅数据

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 01:05:16