Я создал код для извлечения данных из поискового запроса API Youtube:
from apiclient.discovery import build
from apiclient.errors import HttpError
from oauth2client.tools import argparser
from oauth2client import client, GOOGLE_TOKEN_URI
import json
DEVELOPER_KEY = "my key"
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"
def youtube_search(q, max_results=50,order="relevance", token=None, location=None, location_radius=None):
youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, developerKey=DEVELOPER_KEY)
search_response = youtube.search().list(q=q, type="video", pageToken=token, order = order, part="id,snippet", maxResults=max_results, location=location, locationRadius=location_radius).execute()
videos = []
for search_result in search_response.get("items", []):
if search_result["id"]["kind"] == "youtube#video":
videos.append(search_result)
try:
nexttok = search_response["nextPageToken"]
return(nexttok, videos)
except Exception as e:
nexttok = "last_page"
return(nexttok, videos)
, когда я тестирую функцию с поисковым запросом,
youtube_search('sport')
иногда возвращает тайм-аут ошибка :
timeout: The read operation timed out
иногда возвращает ConnectionResetError ошибка :
ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host
, а иногда возвращает только одно видео на каждый токен :
('CDIQAA',
[{'kind': 'youtube#searchResult',
'etag': '"Fznwjl6JEQdo1MGvHOGaz_YanRU/ig3kkPiIvrPIiptur1Y1wpzbSlU"',
'id': {'kind': 'youtube#video', 'videoId': '3TJP5a3pBME'},
'snippet': {'publishedAt': '2018-07-29T16:00:52.000Z',
'channelId': 'UCBINFWq52ShSgUFEoynfSwg',
'title': '20-Minute Victoria Sport Workout For Toned Abs and Legs',
'description': "Stay strong all Summer with Victoria Sport Ambassador Lindsey Harrod's 20-minute high-impact cardio workout. Tone your whole body through circuits including ...",
'thumbnails': {'default': {'url': 'https://i.ytimg.com/vi/3TJP5a3pBME/default.jpg',
'width': 120,
'height': 90},
'medium': {'url': 'https://i.ytimg.com/vi/3TJP5a3pBME/mqdefault.jpg',
'width': 320,
'height': 180},
'high': {'url': 'https://i.ytimg.com/vi/3TJP5a3pBME/hqdefault.jpg',
'width': 480,
'height': 360}},
'channelTitle': 'POPSUGAR Fitness',
'liveBroadcastContent': 'none'}}])
Мне нужна функция для возврата 50 видео за запрос, но функция нестабильна (ошибки) или отказывается возвращать 50 видео.