【问题标题】:KeyError with Youtube API using python使用 python 的 Youtube API 的 KeyError
【发布时间】:2017-03-04 01:47:17
【问题描述】:

这是我第一次在这里提问。我一直在尝试访问 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”)。但是由于某种原因,该代码适用于第一个查询,然后完全失败了第二个查询。这很奇怪,因为它只发生在这个特定元素上。其他一切('description'、'publishedAt' 等)都在工作。这是我的代码:

    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']

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

【问题讨论】:

  • 您的描述中提到了videoID,但代码使用了videoId。 (当然它适用于第一个视频,所以可能只是一个错字?)
  • 是的!你说对了。谢谢!我意识到我从来没有真正感谢你的回答

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


【解决方案1】:

使用 'get' 方法获取结果。

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

有些元素没有这个键。 如果你使用方括号,python 会抛出 exeption keyError,但是如果你使用 'get' 方法,python 返回 None 为没有 key videoId 的元素

【讨论】:

    【解决方案2】:

    因为有些结果要Key "ID",所以返回:

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

    可以看到,没有key“videoId”。

    【讨论】:

      猜你喜欢
      • 2022-01-03
      • 2021-08-09
      • 2016-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多