Created
December 20, 2023 04:25
-
-
Save krisgesling/90ea7561b884fe161b6c705a69fe848d to your computer and use it in GitHub Desktop.
Fetch a list of Youtube videos for a given channel
This file contains hidden or 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 csv | |
import requests | |
def get_videos(channel_id, api_key): | |
# Construct the API request | |
# url = f"https://www.youtube.com/t/videos?part=snippet&q={channel_url}&type=video" | |
url = f"https://www.googleapis.com/youtube/v3/search?key={api_key}&channelId={channel_id}&part=snippet,id&order=date&maxResults=50" | |
# Send the API request and get the response | |
response = requests.get(url) | |
# Parse the JSON response | |
data = response.json() | |
print(data) | |
# Extract the list of videos | |
videos = [] | |
for video in data["items"]: | |
title = video["snippet"]["title"] | |
video_id = video.get("id", {}).get("videoId","ERROR") | |
url = f"http://www.youtube.com/watch?v={video_id}" | |
published_date = video["snippet"].get("publishedAt", "ERROR") | |
#TODO This thumbnail value is only returning error | |
# looks like only "high" resolution is available | |
thumbnail = video["snippet"].get("thumbnails", {}).get("high").get("url", "ERROR") | |
videos.append((title, url, published_date, thumbnail)) | |
# Return the list of videos | |
return videos | |
def write_to_csv(filename, headings, input_data): | |
with open(filename, 'w', newline='') as f: | |
writer = csv.writer(f) | |
writer.writerow(headings) | |
for row in input_data: | |
writer.writerow(row) | |
# Enter your API key and test the function with a sample channel ID | |
api_key = "YOUR_API_KEY" | |
channel_id = "UCUQBwnjgjKyIYll7-PzU8NA" | |
videos = get_videos(channel_id, api_key) | |
headings = ("title", "url", "published at", "thumbnail") | |
write_to_csv("output.csv", headings, videos) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment