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

多YouTube ID执行代码触发KeyError错误,求解决方案

解决YouTube API多频道ID请求的KeyError问题

错误原因分析

  • 列表元素未正确分隔:channel_ids里的各个频道ID之间没加逗号,Python会自动把相邻字符串拼接成一个长ID,导致API请求传入无效参数,返回的response['items']为空或不完整,访问snippet/statistics下的键时触发KeyError。
  • 循环缩进错误:all_data.append(data)写在for循环外面,只会添加最后一次循环的结果,甚至如果循环没执行(比如无有效返回),data未定义还会引发额外错误。
  • 统计字段缺失风险:部分频道可能隐藏订阅数等数据,statistics字典里可能没有subscriberCount这类键,直接访问会触发KeyError。

修正后的代码

from googleapiclient.discovery import build
import pandas as pd
import seaborn as sns

api_key = 'AIzaSy...'

# 修复:给每个频道ID添加逗号,确保是独立列表元素
channel_ids = [
    'UCoUM-UJ7rirJYP8CQ0EIaHA', # Bruno Mars
    'UCqECaJ8Gagnn7YCbPEzWH6g', # Taylor Swift
    'UC9CoOnJkIBMdeijd9qYoT_g', # Ariana Grande
    'UC0C-w0YjGpqDXGB8IHb662A', # Ed Sheeran
    'UCBVjMGOIkavEAhyqpxJ73Dw'  # Maroon 5
]

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

def get_channel_stats(youtube, channel_ids):
    all_data = []
    
    request = youtube.channels().list(
                part='snippet,contentDetails,statistics',
                id=','.join(channel_ids)
                )
    response = request.execute()
    
    # 修复:将append放入循环内,遍历每个频道项并添加数据
    for item in response['items']:
        # 修复:用get方法处理可能缺失的字段,返回默认值避免KeyError
        data = dict(
            channel_name = item['snippet']['title'],
            subscribers = item['statistics'].get('subscriberCount', 'N/A'),
            views = item['statistics'].get('viewCount', 'N/A'),
            total_videos = item['statistics'].get('videoCount', 'N/A')
        )
        all_data.append(data)
   
    return all_data

关键修复说明

  • 给每个频道ID后添加逗号,确保列表包含5个独立的有效ID。
  • 把all_data.append(data)移到for循环内部,保证每个返回的频道数据都被存入列表。
  • 使用字典get()方法访问统计字段,当字段不存在时返回'N/A',避免触发KeyError。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 04:20:32