Python - YouTube API v3 - How to get video ID only?

后端 未结 2 735
盖世英雄少女心
盖世英雄少女心 2021-01-25 16:58

How can I get only video ID of video? As I know, I should use fields for that but I don\'t understand how do they work. My code:

service = build(\'youtube\', \'v         


        
相关标签:
2条回答
  • 2021-01-25 17:18

    Try out below code:

    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']
    
    0 讨论(0)
  • 2021-01-25 17:35

    You can try your query here:

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

    I believe that the following query is the way in what you want to search and retrieve only the video id:

    https://www.googleapis.com/youtube/v3/search?part=id&q={NAME}&type=video&fields=items%2Fid&key={YOUR_API_KEY}

    If for example {NAME} is psy, then this call returns the following data, from where you can retrieve the videoId of one of the items;

    {
     "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"
       }
      }
     ]
    }
    

    if you modify the example included in the python client library:

    https://developers.google.com/api-client-library/python/

    you can do that in this way:

    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"
    
    0 讨论(0)
提交回复
热议问题