python - Youtube API returning 1 video per request or errors
问题描述
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.
解决方案
我有同样的错误,我认为它是由 http 请求没有更新引起的,我通过每次调用请求的函数时构建发现资源来解决它,它对我有用。
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
推荐阅读
- postgresql - PostgresSQL 加密用于具有 1000 万行的列级加密
- python - Pandas 根据条件分组和计算
- django - 在 Heroku 上部署 Django rest-Vue 项目时出现错误 500
- python - 如何使用 Django 过滤小时数?
- java - Spring Jpa Pageable 使用 Java 流获取内容
- python - 加入列表的 2 个元素
- docker - 无法在集群模式下跨覆盖网络中的节点访问服务端口
- java - ViewPager2 在滑动时闪烁/重新加载
- sql - Hive:从一列的不同值中随机选择 N 个值
- c# - ASP.Net Core MVC 如何针对强类型模型发布未知数量的字段