如何从 Youtube Data API v3 获取最大搜索结果? [英] How to get maxresults for search from Youtube Data API v3?

查看:32
本文介绍了如何从 Youtube Data API v3 获取最大搜索结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为特定的 Youtube 搜索查询获得尽可能多的结果.然而,最大没有.可以检索的结果数是50.我知道nextPageToken 可以用来检索下一页的结果.怎么修改python代码实现一样的?

I want to get as many results as possible for a particular Youtube search query. However, the maximum no. of results that can be retrieved is 50. I know that nextPageToken can be used to retrieve results of next page. How do modify the python code to achieve the same?

#!/usr/bin/python
# original source example: https://developers.google.com/youtube/v3/docs/search/list
# assumes use of Python 3

# This sample executes a search request for the specified search term.
# Sample usage:
#   python search.py --q=surfing --max-results=10
# NOTE: To use the sample, you must provide a developer key obtained
#       in the Google APIs Console. Search for "REPLACE_ME" in this code
#       to find the correct place to provide that key..

import argparse

# library googleapiclient installed with: pip install --upgrade google-api-python-client
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError


# Set DEVELOPER_KEY to the API key value from the APIs & auth > Registered apps
# tab of
#   https://cloud.google.com/console
# Please ensure that you have enabled the YouTube Data API for your project.
DEVELOPER_KEY = 'KEY'
YOUTUBE_API_SERVICE_NAME = 'youtube'
YOUTUBE_API_VERSION = 'v3'


def youtube_search(query_term, max_results):
    youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,
        developerKey=DEVELOPER_KEY)

    # Call the search.list method to retrieve results matching the specified
    # query term.
    search_response = youtube.search().list(
        q=query_term,
        part='id,snippet',
        type='video',
        relevanceLanguage='en',
        maxResults=max_results
    ).execute()

    video_ids = []

    # Add each result to the appropriate list, and then display the lists of
    # matching videos, channels, and playlists.
    for search_result in search_response.get('items', []):
        video_ids.append(search_result['id']['videoId'])
    return video_ids


if __name__ == '__main__':
    url_prefix = 'https://www.youtube.com/watch?v='
    query_terms = '"my_query"'
    max_results = 50

    try:
        ids = youtube_search(query_terms, max_results)
    except HttpError as e:
        print('An HTTP error %d occurred:\n%s' % (e.resp.status, e.content))
    else:
        with open('output.txt', 'w') as f:
            for i in ids:
                f.write(url_prefix+i+"\n")

推荐答案

以下是需要添加的内容,以保持获取结果直到找不到 nextPageToken.

Here's what that needs to be added to keep fetching results until no nextPageToken is found.

nextPageToken = search_response.get('nextPageToken')
    while ('nextPageToken' in search_response):
        nextPage = youtube.search().list(
        q=query_term,
        part='id,snippet',
        type='video',
        relevanceLanguage='en',
        maxResults=max_results,
        pageToken=nextPageToken
        ).execute()
        search_response['items'] = search_response['items'] + nextPage['items']

        if 'nextPageToken' not in nextPage:
            search_response.pop('nextPageToken', None)
        else:
            nextPageToken = nextPage['nextPageToken']

这篇关于如何从 Youtube Data API v3 获取最大搜索结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆