Created
February 21, 2024 16:47
-
-
Save alexdwagner/896f8bdeaa96cd17926164f2c3b6ff12 to your computer and use it in GitHub Desktop.
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
# This is a simple Python script that fetches a list of videos with their details and outputs a CSV. | |
# Right now, maxResults is set to 50, but change as needed, and as API rate-limiting will allow. | |
# You need a Google/Youtube API key to run this script. | |
import os | |
import csv | |
from googleapiclient.discovery import build | |
# Simplified configuration; ensure you have these values correctly set up | |
API_KEY = 'YOUR_API_KEY' | |
CHANNEL_ID = 'TARGET_CHANNEL_ID' # Replace with the channel ID you want to scrape | |
def build_youtube_service(api_key): | |
"""Build and return the YouTube service object.""" | |
return build("youtube", "v3", developerKey=api_key) | |
def get_all_videos(youtube, channel_id): | |
"""Retrieve all video details from a specific channel.""" | |
videos = [] | |
request = youtube.search().list( | |
channelId=channel_id, | |
type='video', | |
part='id,snippet', | |
maxResults=50 # Adjust as necessary, respecting API quotas | |
) | |
while request: | |
response = request.execute() | |
videos.extend(response['items']) | |
request = youtube.search().list_next(request, response) | |
return videos | |
def save_videos_to_csv(videos, csv_file="videos.csv"): | |
"""Save video details to a CSV file.""" | |
with open(csv_file, mode="w", newline="", encoding='utf-8') as file: | |
writer = csv.writer(file) | |
writer.writerow(["Video ID", "Title", "Published At"]) | |
for video in videos: | |
video_id = video['id']['videoId'] | |
title = video['snippet']['title'] | |
published_at = video['snippet']['publishedAt'] | |
writer.writerow([video_id, title, published_at]) | |
def main(): | |
youtube = build_youtube_service(API_KEY) | |
videos = get_all_videos(youtube, CHANNEL_ID) | |
save_videos_to_csv(videos) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment