使用 python 的 Youtube API KeyError [英] KeyError with Youtube API using python

查看:27
本文介绍了使用 python 的 Youtube API KeyError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我第一次在这里提问.我一直在尝试访问 Youtube API 以获得我正在做的实验的一些东西.到目前为止一切正常.我只是想问一下我得到的这个非常不一致的错误.

This is my first time to ask something here. I've been trying to access the Youtube API to get something for an experiment I'm doing. Everything's working so far. I just wanted to ask about this very inconsistent error that I'm getting.

-----------
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").但是出于某种原因,该代码适用于第一个查询,然后完全失败用于第二个查询.这很奇怪,因为它只发生在这个特定元素上.其他所有内容(描述"、发布时间"等)都在工作.这是我的代码:

I tried getting the video ID ('videoID' as per documentation). But for some reason, the code works for the 1st query, and then totally flops for the 2nd one. It's weird because it's only happening for this particular element. Everything else ('description','publishedAt', etc.) is working. Here's my code:

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

希望大家帮帮我.谢谢!

Hope you guys can help me. Thanks!

推荐答案

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

Use 'get' method for result.

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

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

there are in some element no this key. if you use square parenteces, python throw exeption keyError, but if you use 'get' method, python return None for element whitch have not key videoId

这篇关于使用 python 的 Youtube API KeyError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆