如何通过ID使用Youtube API v3获取单个视频。
到目前为止,我只遇到了搜索机制和其他机制,但没有具体地看到一个获取单个视频的机制,我目前的代码是:
def youtube_search(q, max_results=1,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)但我意识到这种方法不是有效的,而是浪费时间和资源。我该怎么做呢?
发布于 2018-09-13 23:12:41
YouTube API搜索调用用于搜索。您希望使用视频呼叫并传入要查询的视频ID。
示例:
https://www.googleapis.com/youtube/v3/videos?part=snippet&id=xE_rMj35BIM&key=YOUR_KEY发布于 2020-04-09 09:41:55
在Google控制台和操场中配置api。获取api密钥并访问令牌,然后调用此API以通过Id获取视频。
您也可以在这里测试链接
GET https://www.googleapis.com/youtube/v3/videos?part=snippet&id=vuKRKt7aKpE&key=[YOUR_API_KEY]
Authorization: Bearer [YOUR_ACCESS_TOKEN]
Accept: application/json发布于 2022-02-16 22:39:05
要在Python中访问特定的视频,可以使用video()方法而不是search(),并在list()方法中使用参数id。id是一个参数,可以在Youtube视频的https://www.youtube.com/watch?v={video_id}[&{otherParameters}={values}]格式的URL中找到(例如https://www.youtube.com/watch?v=qEB0FIBoKAg&t=15s)。在您的URL中,v的值(在"=“符号之后)是您当前正在观看的视频的ID。"&“符号意味着添加其他参数(在这里,t是”视频的开始时间“,从15秒开始)。
我是如何在代码中这样做的:
...
# Create API service
serv = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, developerKey=DEVELOPER_KEY)
# Make request. part must be "snippet", id is your video, and maxResults is optional
req = serv.videos().list(part = "snippet", id = video_id, maxResults = 1)
# get the JSON file (can be accessed as a dictionary)
response = req.execute()
# Access the (standard) thumbnail (URL)
sd_thumbnail = response["items"][0]["snippet"]["thumbnails"]["standard"]["url"]
# If you want other resolutions than "standard" you can change it into "default", "medium" or "high"
print(sd_thumbnail)此程序将打印:
https://i.ytimg.com/vi/qEB0FIBoKAg/sddefault.jpg它的格式是https://i.ytimg.com/vi/{video_id}/{file}.jpg而不是file,这里可以是“默认”、"mqdefault“、"hqdefault”和"sddefautl“。
Youtube有关于他们的API的很好的文档。有关您的问题的更多信息可以在https://developers.google.com/youtube/v3/docs/videos/list中找到答案。
https://stackoverflow.com/questions/52302427
复制相似问题