Created
January 30, 2017 16:22
-
-
Save psidex/6a4eacd913564606125005e36bcd94bc to your computer and use it in GitHub Desktop.
Get all video links from a Youtube playlist
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests | |
import json | |
""" | |
The Youtube API only provides a certain amount of results per page, so if there | |
are lots of videos in a playlist it will need multiple pages to get all the videos | |
""" | |
# EDIT THESE | |
api_key = "YOUTUBE V3 API KEY" | |
playlist_link = "YOUTUBE PLAYLIST LINK" | |
# | |
# Request youtube API without pageToken (first page/only 1 page) | |
req_no_token = "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=40&playlistId={}&fields=items(snippet(resourceId(playlistId%2CvideoId)))%2CnextPageToken&key={}" | |
# Request youtube API with pageToken (pages 2+) | |
req_with_token = "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=40&pageToken={}&playlistId={}&fields=items(snippet(resourceId(playlistId%2CvideoId)))%2CnextPageToken&key={}" | |
videos = [] | |
ids = "" # Will be set to returned json | |
def get_video_links(url): | |
global ids | |
info = requests.get(url) # Request info | |
ids = json.loads(info.text) # Parse the json that is returned | |
for snippet in ids["items"]: # Get all video ID's from current page of results | |
video_id = snippet["snippet"]["resourceId"]["videoId"] | |
videos.append("https://www.youtube.com/watch?v={}".format(video_id)) | |
playlist_id = playlist_link.split("list=")[1] # Get playlist ID | |
get_video_links(req_no_token.format(playlist_id, api_key)) # Get video links for first page | |
while 1: | |
try: # Only works if there is a pageToken | |
nextpagetoken = ids["nextPageToken"] | |
print("Next page", nextpagetoken) | |
get_video_links(req_with_token.format(nextpagetoken, playlist_id, api_key)) | |
except KeyError: | |
break # No next page | |
# Display results | |
print("\nRESULTS:\n") | |
print("\n".join(videos)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment