python 在youtube ape上执行我的代码时出现KeyError(多个youtube ID)

aurhwmvo  于 2023-01-08  发布在  Python
关注(0)|答案(1)|浏览(135)

我有一个问题时,执行我的代码与多个youtube的id,这里是我的代码

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

api_key = 'AIzaSy...'

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()
    
    for i in range(len(response['items'])):
         data = dict(channel_name = response['items'][i]['snippet']['title'],
                subscribers = response['items'][i]['statistics']['subscriberCount'],
                views = response['items'][i]['statistics']['viewCount'],
                total_videos = response['items'][i]['statistics']['videoCount']) 
    all_data.append(data)
   
    
    return all_data

然而,当我运行代码时,它显示此错误
enter image description here
对此有什么解决办法吗?

4xrmg8kj

4xrmg8kj1#

变更:

channel_ids = ['UCoUM-UJ7rirJYP8CQ0EIaHA' #Bruno Mars
               'UCqECaJ8Gagnn7YCbPEzWH6g' #Taylor Swift
               'UC9CoOnJkIBMdeijd9qYoT_g' #Ariana Grande
               'UC0C-w0YjGpqDXGB8IHb662A' #Ed Sheeran
               'UCBVjMGOIkavEAhyqpxJ73Dw'] #Maroon 5

致:

channel_ids = ['UCoUM-UJ7rirJYP8CQ0EIaHA', #Bruno Mars
               'UCqECaJ8Gagnn7YCbPEzWH6g', #Taylor Swift
               'UC9CoOnJkIBMdeijd9qYoT_g', #Ariana Grande
               'UC0C-w0YjGpqDXGB8IHb662A', #Ed Sheeran
               'UCBVjMGOIkavEAhyqpxJ73Dw'] #Maroon 5

在我这边解决了问题。
注意四个逗号的引入。

相关问题