import os

from googleapiclient.discovery import build
import csv

# Replace with your API key
API_KEY = "your api key"

# Create a YouTube Data API client
youtube = build("youtube", "v3", developerKey=API_KEY)

def get_channel_videos(channel_id):
videos = []
next_page_token = None

# Get the "uploads" playlist ID for the channel
channels_response = youtube.channels().list(
id=channel_id,
part='contentDetails'
).execute()

uploads_playlist_id = channels_response['items'][0]['contentDetails']['relatedPlaylists']['uploads']

while True:
# Fetch the videos in the "uploads" playlist
playlist_items_request = youtube.playlistItems().list(
playlistId=uploads_playlist_id,
part='snippet',
maxResults=50,
pageToken=next_page_token
)
playlist_items_response = playlist_items_request.execute()

# Extract video IDs
video_ids = [item['snippet']['resourceId']['videoId'] for item in playlist_items_response['items']]

# Fetch video details and statistics for each video ID
videos_request = youtube.videos().list(
part="snippet,statistics",
id=','.join(video_ids)
)
videos_response = videos_request.execute()

# Process each video
for item in videos_response['items']:
video = {
"title": item['snippet']['title'],
"views": item['statistics']['viewCount'],
"video_link": f"https://www.youtube.com/watch?v={item['id']}"
}
videos.append(video)

# Check if there are more pages of results
next_page_token = playlist_items_response.get("nextPageToken")
if not next_page_token:
break

return videos

def save_to_csv(videos, file_path):
# Define the field names (columns) for the CSV file
field_names = ["Title", "Views", "Video Link"]

# Write the video information to the CSV file
with open(file_path, mode="w", newline="", encoding="utf-8") as file:
writer = csv.DictWriter(file, fieldnames=field_names)
writer.writeheader()
for video in videos:
writer.writerow({
"Title": video["title"],
"Views": video["views"],
"Video Link": video["video_link"]
})

if __name__ == "__main__":
channel_id = "UCnojtUuLoLdQQaKBou5bR4g" # Replace with the channel ID of the target channel
videos = get_channel_videos(channel_id)

# Specify the path where you want to save the CSV file
csv_file_path = "/Users/jitendersingh/Downloads/videos_info.csv"

# Save video information to the CSV file
save_to_csv(videos, csv_file_path)
print("Video information saved to", csv_file_path)

0 comments:

Post a Comment

 
Top