Python - YouTube API v3 - 如何仅获取视频ID?

时间:2013-01-25 19:25:24

标签: python youtube-api

如何只获取视频的视频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 :(得分:2)

您可以在此处尝试查询:

https://developers.google.com/youtube/v3/docs/search/list#try-it

我相信以下查询是您想要搜索和检索视频ID的方式:

https://www.googleapis.com/youtube/v3/search?part=id&q= {NAME}&安培;类型=视频&安培;字段=项%2Fid&安培;关键= {} 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"

答案 1 :(得分: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']