Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...