如何只获取视频的视频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()
"名称"是搜索词变量。我从一个包含名称列表的文件中获取它。通过使用这段代码,我得到了我不需要的信息。正如我所说,我只需要视频ID。
您可以在此处尝试查询:
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,则此调用返回以下数据,您可以从中检索其中一个项目的 videoId;
{
"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"
尝试以下代码:
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']