Python - YouTube API v3 - 如何仅获取视频ID?
我想知道怎么只获取视频的ID。我知道应该使用字段来做到这一点,但我不太明白这些字段是怎么工作的。我的代码是:
service = build('youtube', 'v3', developerKey = api_key)
request = service.search().list(q = name, part='id',fields = *what should I type here*, maxResults = 1, type = 'video').execute()
“name”是搜索关键词的变量。我是从一个包含名字列表的文件中获取这个变量的。用这段代码我得到了我不需要的信息。正如我所说,我只需要视频的ID。
2 个回答
0
试试下面的代码:
import requests
import json
payload = {'part': 'snippet', 'key': DEVELOPER_KEY, 'order':'viewCount', 'q': 'A R Rahman', 'maxResults': 1}
l = requests.Session().get('https://www.googleapis.com/youtube/v3/search', params=payload)
resp_dict = json.loads(l.content)
print resp_dict['items']
for i in resp_dict['items']:
print "VideoId: ",i['id']['videoId']
2
你可以在这里试试你的查询:
https://developers.google.com/youtube/v3/docs/search/list#try-it
我认为下面这个查询可以帮助你搜索并只获取视频的ID:
https://www.googleapis.com/youtube/v3/search?part=id&q={NAME}&type=video&fields=items%2Fid&key={YOUR_API_KEY}
比如说,如果{NAME}是psy,那么这个请求会返回一些数据,你可以从中找到其中一个视频的ID;
{
"items": [
{
"id": {
"kind": "youtube#video",
"videoId": "9bZkp7q19f0"
}
},
{
"id": {
"kind": "youtube#video",
"videoId": "Ecw4O5KgvsU"
}
},
{
"id": {
"kind": "youtube#video",
"videoId": "o443b2rfFnY"
}
},
{
"id": {
"kind": "youtube#video",
"videoId": "WOyo7JD7hjo"
}
},
{
"id": {
"kind": "youtube#video",
"videoId": "QZmkU5Pg1sw"
}
}
]
}
如果你修改一下Python客户端库中的示例:
https://developers.google.com/api-client-library/python/
你可以这样做:
search_response = service.search().list(
q="google",
part="id",
type="video",
fields="items/id"
).execute()
videos = []
for search_result in search_response.get("items", []):
videos.append("%s" % (search_result["id"]["videoId"]))
print "Videos:\n", "\n".join(videos), "\n"