Advertisement
J2897

[YouTube API] Average Views (synchronous)

Feb 18th, 2022
1,186
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.62 KB | None | 0 0
  1. import requests
  2. import time
  3. from config import api_key, channel_id, base_url
  4.  
  5. start_time = time.time()
  6.  
  7. # Get the ID from the Uploads Playlist.
  8. url = f'{base_url}/channels?id={channel_id}&key={api_key}&part=contentDetails'
  9. r = requests.get(url)
  10. results = r.json()['items']
  11. playlist_id = results[0]['contentDetails']['relatedPlaylists']['uploads']
  12.  
  13. # Get all of the video IDs.
  14. video_ids = []
  15. url = f'{base_url}/playlistItems?playlistId={playlist_id}&key={api_key}&part=contentDetails'
  16. while True:
  17.     r = requests.get(url)
  18.     results = r.json()
  19.     if 'nextPageToken' in results:
  20.         nextPageToken = results['nextPageToken']
  21.     else:
  22.         nextPageToken = None
  23.  
  24.     if 'items' in results:
  25.         for item in results['items']:
  26.             if 'contentDetails' in item:
  27.                 if 'videoId' in item['contentDetails']:
  28.                     videoId = item['contentDetails']['videoId']
  29.                     video_ids.append(videoId)
  30.  
  31.     if nextPageToken:
  32.         url = f'{base_url}/playlistItems?playlistId={playlist_id}&key={api_key}&part=contentDetails&pageToken={nextPageToken}'
  33.     else:
  34.         break
  35.  
  36. # Get all of the videos' view counts.
  37. view_counts = []
  38. for video_id in video_ids:
  39.     url = f'{base_url}/videos?id={video_id}&key={api_key}&part=statistics'
  40.     r = requests.get(url)
  41.     results = r.json()['items']
  42.     viewCount = results[0]['statistics']['viewCount']
  43.     view_counts.append(int(viewCount))
  44.  
  45. print('Number of videos:', 2*'\t', len(view_counts))
  46. print('Average number of views:', '\t', sum(view_counts) / len(view_counts))
  47. print("--- %s seconds ---" % (time.time() - start_time))
  48.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement