使用python的Youtube API的KeyError

时间:2016-10-21 16:55:42

标签: python api youtube youtube-data-api keyerror

这是我第一次在这里问一些问题。我一直在尝试访问Youtube API以获取我正在进行的实验。到目前为止一切正常。我只想问一下我得到的这个非常不一致的错误。

-----------
1
Title:  All Movie Trailers of New York Comic-Con (2016) Power Rangers, John Wick 2...
Uploaded by:    KinoCheck International
Uploaded on:    2016-10-12T14:43:42.000Z
Video ID:   pWOH-OZQUj0
2
Title:  Movieclips Trailers
Uploaded by:    Movieclips Trailers
Uploaded on:    2011-04-01T18:43:14.000Z
Video ID:   Traceback (most recent call last):
  File "scrapeyoutube.py", line 24, in <module>
    print "Video ID:\t", search_result['id']['videoId']
KeyError: 'videoId'

我尝试获取视频ID(根据文档提供'videoID')。但由于某种原因,代码适用于第一个查询,然后完全翻转第二个查询。这很奇怪,因为它只发生在这个特定元素上。其他一切('描述','已发布'等)正在发挥作用。这是我的代码:

    from apiclient.discovery import build
import json
import pprint
import sys

APINAME = 'youtube'
APIVERSION = 'v3'
APIKEY = 'secret teehee'

service = build(APINAME, APIVERSION, developerKey = APIKEY)

#volumes source ('public'), search query ('androide')
searchrequest = service.search().list(q ='movie trailers', part ='id, snippet', maxResults = 25).execute()

searchcount = 0
print "-----------"
for search_result in searchrequest.get("items", []):
    searchcount +=1
    print searchcount
    print "Title:\t", search_result['snippet']['title']
    # print "Description:\t", search_result['snippet']['description']
    print "Uploaded by:\t", search_result['snippet']['channelTitle']
    print "Uploaded on:\t", search_result['snippet']['publishedAt']
    print "Video ID:\t", search_result['id']['videoId']

希望你们能帮助我。谢谢!

2 个答案:

答案 0 :(得分:0)

对结果使用'get'方法。

result['id'].get('videoId')

在某些元素中没有此键。 如果使用方括号,则python抛出exeption keyError,但是如果使用'get'方法,则python对于元素的返回值None则没有key videoId

答案 1 :(得分:-1)

因为某些结果为Key“ID”,请返回:

{u'kind': u'youtube#playlist', u'playlistId': u'PLd0_QArxznVHnlvJp0ki5bpmBj4f64J7P'}

你可以看到,没有关键的“videoId”。