YouTubeのAPIを使用して動画のタイトルとURLの一覧を取得するプログラムを作成した時のメモ。
import csv from googleapiclient.discovery import build # YouTube Data API キーを設定 API_KEY = '' # チャンネルURLを設定 CHANNEL_URL='' def get_channel_videos(channel_url): # YouTube APIクライアントを作成 youtube = build('youtube', 'v3', developerKey=API_KEY) # チャンネルIDを取得 channel_id = channel_url.split('/')[-1] # チャンネルの動画を取得 videos = [] next_page_token = None while True: request = youtube.search().list( part='snippet', channelId=channel_id, maxResults=50, type='video', pageToken=next_page_token ) response = request.execute() for item in response['items']: video_title = item['snippet']['title'] video_url = f"https://www.youtube.com/watch?v={item['id']['videoId']}" videos.append({'title': video_title, 'url': video_url}) next_page_token = response.get('nextPageToken') if not next_page_token: break return videos def main(): video_list = get_channel_videos(CHANNEL_URL) with open('video_list.csv', mode='w', newline='', encoding='utf-8') as file: writer = csv.writer(file) writer.writerow(['title', 'url']) for video in video_list: writer.writerow([video['title'], video['url']]) if __name__ == "__main__": main()