Reputation: 92
I created code to extract data from Youtube API search query:
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)
when I test the function with the search query,
youtube_search('sport')
sometimes return a timeout error:
timeout: The read operation timed out
sometimes return ConnectionResetError error:
ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host
and sometimes it return only one video per token:
('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'}}])
I need the function to return 50 videos per request but the function is unstable (errors) or refuse to return 50 videos.
Upvotes: 0
Views: 121
Reputation: 26
I had the same error and i think it is caused by the http request does not update and i solved it by building the discovery resource every single time that i called the function of the request and it worked for me.
from googleapiclient.discovery import build
import time
def url_sinffer(search_word):
api_key = "Your Api key"
youtube = build('youtube', 'v3', developerKey=api_key)
print(type(youtube))
request = youtube.search().list(
part="id",
q=search_word,
maxResults=1,
type="music"
)
response = request.execute()
time.sleep(0.5)
video_id = response['items'][0]['id']['videoId']
url = f'https://www.youtube.com/watch?v={video_id}'
return url
Upvotes: 1