Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import aiohttp
- import asyncio
- 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
- async def main():
- async with aiohttp.ClientSession() as session:
- tasks = []
- for video_id in video_ids:
- task = asyncio.ensure_future(get_video_data(session, video_id))
- tasks.append(task)
- view_counts = await asyncio.gather(*tasks)
- print('Number of videos:', 2*'\t', len(view_counts))
- print('Average number of views:', '\t', sum(view_counts) / len(view_counts))
- async def get_video_data(session, video_id):
- url = f'{base_url}/videos?id={video_id}&key={api_key}&part=statistics'
- async with session.get(url) as response:
- result_data = await response.json()
- results = result_data['items']
- viewCount = results[0]['statistics']['viewCount']
- return int(viewCount)
- asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
- asyncio.run(main())
- print("--- %s seconds ---" % (time.time() - start_time))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement