通过YouTube API v3 从多个频道获取最近上传的高效方法

5 投票
1 回答
1005 浏览
提问于 2025-04-18 06:52

我有一串频道的ID,比如:

channel_ids = ['UC6nSFpj9HTCZ5t-N3Ra3-HB', 'UC6nSFpjSEBUCZ5t-N3Ra3-HB', 'UC6nrst90rsd3Z5t-N3Ra3-HC', 'UC6nSFpjd329th0rt-tuTH3-HA']

我想用YouTube数据API v3来获取这些频道最近上传的50个视频,尽量减少网络请求的次数和时间。

我现在的做法是:

from apiclient.discovery import build

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

channel_ids = ['UC6nSFpj9HTCZ5t-N3Ra3-HB', 'UC6nSFpjSEBUCZ5t-N3Ra3-HB', 'UC6nrst90rsd3Z5t-N3Ra3-HC', 'UC6nSFpjd329th0rt-tuTH3-HA']
videos_by_channel = {}

for channel_id in channel_ids:

    search_response = youtube.search().list(part="id",
                                            type='video',
                                            order='date',
                                            channelId=channel_id,
                                            maxResults=50).execute()

    videoIds = []
    for search_result in search_response.get("items", []):
        if search_result["id"]["kind"] == "youtube#video":
            videoIds.append(search_result['id']['videoId'])

    search_response = youtube.videos().list(
                                            id=",".join(videoIds),
                                            part="id,snippet"
                                            ).execute()

    videos_by_channel[channel_id] = search_response

这个方法能用,但调用服务器的次数太多,而且速度也不快。我看过文档,但找不到更快的方法,有什么好主意吗?

1 个回答

1

你可以通过发送批量请求的方式,一次发送多个请求。

撰写回答