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

如何通过Python批量订阅YouTube频道(基于Channel_ID)

YouTube订阅批量迁移解决方案

问题原因

你当前代码里的字典存在键重复问题:'snippet.resourceId.channelId'被赋值两次,后一个值会直接覆盖前一个,所以只会执行最后一个频道的订阅请求。

修改方案

我们需要把频道ID整理成一个列表,然后循环调用订阅函数,逐个处理每个频道:

完整修改后的代码

import os
import time
import google.oauth2.credentials
import google_auth_oauthlib.flow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from google_auth_oauthlib.flow import InstalledAppFlow

CLIENT_SECRETS_FILE = "client_secret.json"
SCOPES = ['https://www.googleapis.com/auth/youtube.force-ssl']
API_SERVICE_NAME = 'youtube'
API_VERSION = 'v3'

def get_authenticated_service():
    flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRETS_FILE, SCOPES)
    credentials = flow.run_console()
    return build(API_SERVICE_NAME, API_VERSION, credentials=credentials)

def print_response(response):
    print(f"成功订阅频道: {response['snippet']['resourceId']['channelId']}")

def build_resource(properties):
    resource = {}
    for p in properties:
        prop_array = p.split('.')
        ref = resource
        for pa in range(len(prop_array)):
            is_array = False
            key = prop_array[pa]
            if key[-2:] == '[]':
                key = key[:-2]
                is_array = True
            if pa == len(prop_array) - 1:
                if properties[p]:
                    if is_array:
                        ref[key] = properties[p].split(', ')
                    else:
                        ref[key] = properties[p]
            elif key not in ref:
                ref[key] = {}
                ref = ref[key]
            else:
                ref = ref[key]
    return resource

def remove_empty_kwargs(**kwargs):
    good_kwargs = {}
    if kwargs:
        for key, value in kwargs.items():
            if value:
                good_kwargs[key] = value
    return good_kwargs

def subscriptions_insert(client, channel_id):
    # 针对单个频道构建订阅参数
    properties = {
        'snippet.resourceId.kind': 'youtube#channel',
        'snippet.resourceId.channelId': channel_id
    }
    resource = build_resource(properties)
    kwargs = remove_empty_kwargs(part='snippet')
    try:
        response = client.subscriptions().insert(body=resource, **kwargs).execute()
        print_response(response)
    except HttpError as e:
        print(f"订阅频道 {channel_id} 失败: {e}")

if __name__ == '__main__':
    os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'
    client = get_authenticated_service()
    
    # 把需要订阅的所有频道ID放在这个列表里
    channel_ids = [
        'UC09fL42MpkktKZWmWxYiDhw',
        'UC0Q7Hlz75NYhYAuq6O0fqHw',
        # 继续添加更多频道ID即可
    ]
    
    # 循环遍历列表,逐个订阅(加入延时避免API限流)
    for channel_id in channel_ids:
        subscriptions_insert(client, channel_id)
        time.sleep(1)

关键修改点

  • 将多个频道ID存入列表channel_ids,彻底解决字典键覆盖问题
  • 重构subscriptions_insert函数,改为接收单个频道ID作为参数,每次只处理一个订阅请求
  • 增加异常捕获,处理订阅失败的情况(比如频道不存在、权限不足等)
  • 添加time.sleep(1)避免API请求过于频繁触发限流,适配470+订阅的批量操作
  • 优化打印信息,明确显示每个频道的订阅状态

扩展建议

如果要从旧账号迁移全部订阅:

  • 可以调用YouTube数据API的subscriptions.list接口,获取旧账号的所有订阅频道ID,直接导入到channel_ids列表中
  • 若订阅数量极大,可将频道ID存入文本文件,通过读取文件批量加载,避免代码里硬编码过多内容

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 19:30:39