Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
409 views
in Technique[技术] by (71.8m points)

KeyError with Youtube API using python

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:	", search_result['id']['videoId']
KeyError: '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:	", search_result['snippet']['title']
    # print "Description:	", search_result['snippet']['description']
    print "Uploaded by:	", search_result['snippet']['channelTitle']
    print "Uploaded on:	", search_result['snippet']['publishedAt']
    print "Video ID:	", search_result['id']['videoId']

Hope you guys can help me. Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use 'get' method for result.

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...