askcompu

Untitled

Jul 21st, 2015
307
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.12 KB | None | 0 0
  1. def query(vid, auth_key):
  2.     '''
  3.    returns the title, viewcount, time, and uploader of a Youtube video.
  4.    vid is the Youtube video ID at the end of the Youtube URL.
  5.    '''
  6.    
  7.     main = 'https://www.googleapis.com/youtube/v3/videos?id='
  8.     key = '&key=' + auth_key
  9.     ext = '&part=snippet,contentDetails,statistics'
  10.    
  11.     req = web.get(main + vid + key + ext)
  12.     data = json.loads(req, encoding='utf-8')
  13.     data = data['items'][0]
  14.    
  15.     title = data['snippet']['title']
  16.     uploader = data['snippet']['channelTitle']
  17.     try:
  18.         viewcount = str(data['statistics']['viewCount'])
  19.     except (KeyError, IndexError):
  20.         viewcount = '0'
  21.     duration = str(data['contentDetails']['duration'])
  22.     # a video with no likes results in IndexErrors (assuming true for ratingCount, too)
  23.     try:
  24.         likes = str(data['statistics']['likeCount'])
  25.     except (KeyError, IndexError):
  26.         likes = '0'
  27.     try:
  28.         dislikes = str(data['statistics']['dislikeCount'])
  29.     except (KeyError, IndexError):
  30.         dislikes = '0'
  31.    
  32.     time = iso_8601(duration)
  33.    
  34.     return title, viewcount, time, uploader, likes, dislikes
Advertisement
Add Comment
Please, Sign In to add comment