如何从 Youtube Data API v3 获取最大搜索结果?
Posted
技术标签:
【中文标题】如何从 Youtube Data API v3 获取最大搜索结果?【英文标题】:How to get maxresults for search from Youtube Data API v3? 【发布时间】:2019-06-14 10:22:03 【问题描述】:我希望针对特定的 Youtube 搜索查询获得尽可能多的结果。但是,最大没有。可以检索的结果是 50。我知道可以使用 nextPageToken 检索下一页的结果。如何修改python代码实现相同?
#!/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")
【问题讨论】:
【参考方案1】:这是需要添加的内容以继续获取结果,直到找不到 nextPageToken。
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 获取最大搜索结果?的主要内容,如果未能解决你的问题,请参考以下文章
YouTube Data v3 API - 如何从频道请求所有视频?
如何使用 YouTube Data API v3 更改页面结果
如何通过 YouTube Data API v3 从我自己的 YouTube 频道获取所有视频
YouTube 频道中的“已发布视频”和“上传”有啥区别?以及如何通过 YouTube Data v3 API 获取它们?