Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import requests
- import time
- from config import api_key, channel_id, base_url
- start_time = time.time()
- # Get the ID from the Uploads Playlist.
- url = f'{base_url}/channels?id={channel_id}&key={api_key}&part=contentDetails'
- r = requests.get(url)
- results = r.json()['items']
- playlist_id = results[0]['contentDetails']['relatedPlaylists']['uploads']
- # Get all of the video IDs.
- video_ids = []
- url = f'{base_url}/playlistItems?playlistId={playlist_id}&key={api_key}&part=contentDetails'
- while True:
- r = requests.get(url)
- results = r.json()
- if 'nextPageToken' in results:
- nextPageToken = results['nextPageToken']
- else:
- nextPageToken = None
- if 'items' in results:
- for item in results['items']:
- if 'contentDetails' in item:
- if 'videoId' in item['contentDetails']:
- videoId = item['contentDetails']['videoId']
- video_ids.append(videoId)
- if nextPageToken:
- url = f'{base_url}/playlistItems?playlistId={playlist_id}&key={api_key}&part=contentDetails&pageToken={nextPageToken}'
- else:
- break
- # Get all of the videos' view counts.
- view_counts = []
- for video_id in video_ids:
- url = f'{base_url}/videos?id={video_id}&key={api_key}&part=statistics'
- r = requests.get(url)
- results = r.json()['items']
- viewCount = results[0]['statistics']['viewCount']
- view_counts.append(int(viewCount))
- print('Number of videos:', 2*'\t', len(view_counts))
- print('Average number of views:', '\t', sum(view_counts) / len(view_counts))
- print("--- %s seconds ---" % (time.time() - start_time))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement