获取只有 Youtube 字幕的视频列表 API

Get List of Videos that Only Have Subtitles Youtube API

我有一个 python 代码可以使用 Youtube API 搜索视频。
我的输出目标是检索只有 subtitles/CC 的视频,就像 Youtube Web 上的搜索过滤器一样。

我当前的代码:

videos = []
def get_videos_by_query(query: str, maxResults: int = 50, pageToken: str = None):
    youtube = build(YOUTUBE_API_SERVICE_NAME,
              YOUTUBE_API_VERSION,
              developerKey=DEVELOPER_KEY)
    try:
        search_response = youtube.search().list(
            part="id,snippet",
            order='date',
            maxResults=maxResults,
            pageToken=pageToken,
            q=query
            ).execute()

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

    except Exception as e:
        print(e)

我怎样才能做到这一点?

根据 Search.list API 端点的文档,为了在获得的结果集上实现所需的过滤,您应该使用以下参数:

videoCaption (string)

The videoCaption parameter indicates whether the API should filter video search results based on whether they have captions. If you specify a value for this parameter, you must also set the type parameter's value to video.

Acceptable values are:

  • any – Do not filter results based on caption availability.
  • closedCaption – Only include videos that have captions.
  • none – Only include videos that do not have captions.

因此,请将上面对 youtube.search().list() 的调用替换为以下调用:

search_response = youtube.search().list(
        part="id,snippet",
        order='date',
        type='video',
        videoCaption='closedCaption',
        maxResults=maxResults,
        pageToken=pageToken,
        q=query
        ).execute()

请注意,通过此更改,以下代码片段变得多余:

if search_result["id"]["kind"] == "youtube#video":

这是因为,通过在 API 端点的调用中使用 type='video',获得的结果集中的每一项都必然引用视频。