使用Python与YouTube Data v3 API获取频道TAG及ID
解决YouTube频道ID与@TAG同步获取的问题
现有代码仅能从URL提取频道ID,无法获取@形式的频道TAG(如@MrBeast),可通过调用YouTube Data API的channels.list接口获取该信息,以下是修改后的完整实现:
核心修改点
- 调用API获取频道
snippet元数据,从中提取自定义TAG字段 - 处理频道未设置自定义TAG的边界情况
- 将TAG信息存入结果字典并写入输出文件
修改后的完整代码
from googleapiclient.discovery import build import yaml # 替换为你的YouTube Data API密钥 api_key = "YOUR_API_KEY" with open('data/data.yml', 'r') as yaml_file: data = yaml.safe_load(yaml_file) channel_urls = [channel['url'] for channel in data['channels']] youtube = build('youtube', 'v3', developerKey=api_key) channel_results = [] for channel_url in channel_urls: channel_id = channel_url.split('/')[-1] try: # 调用API获取频道snippet信息 request = youtube.channels().list( part="snippet", id=channel_id ) response = request.execute() if response['items']: snippet = response['items'][0]['snippet'] # 提取@形式TAG,无自定义TAG则设为None channel_tag = f"@{snippet['customUrl']}" if 'customUrl' in snippet else None channel_info = { 'url': channel_url, 'id': channel_id, 'tag': channel_tag, 'channel_name': snippet['title'] # 可选:同步获取频道名称 } channel_results.append(channel_info) # 打印处理结果 print(f"已处理频道数: {len(channel_results)}\n") print(f"频道URL: {channel_url}") print(f"频道ID: {channel_id}") print(f"频道TAG: {channel_tag if channel_tag else '无自定义TAG'}") print(f"频道名称: {snippet['title']}\n") else: print(f"未找到对应频道信息: {channel_url}\n") except Exception as e: print(f"获取频道信息出错: {channel_url}") print(f"错误详情: {str(e)}\n") # 写入结果文件 with open('output/channel_results.yml', 'w', encoding='utf-8') as yaml_file: yaml_file.write(f"Nombre de chaînes : {len(channel_results)}\n") yaml.dump({'channels': channel_results}, yaml_file, allow_unicode=True)
注意事项
- 需先安装依赖:
pip install google-api-python-client - YouTube Data API有配额限制,批量处理时需控制请求频率
- 部分频道未设置自定义TAG,此时
tag字段会返回None,可根据需求调整默认显示内容
内容的提问来源于stack exchange,提问作者JasonStatham
相关产品推荐
相关产品推荐

