CSVは、”検索ワード_result.csv”でワークスペースに保存される。
import os import csv from googleapiclient.discovery import build ws = "ここにワークスペースを入力" os.chdir(ws) # YouTube APIキーを設定 api_key = "ここに自分のAPIキーを入力してください" #keyword keyword = "keywordを入力" # YouTube APIのビルド youtube = build('youtube', 'v3', developerKey=api_key) def search_youtube_videos(keyword, max_results=200): # YouTube APIを使用して動画を検索 search_response = youtube.search().list( q=keyword, type='video', part='id,snippet', maxResults=max_results ).execute() #csvファイルの名前 csv_name = keyword + "_result.csv" # 検索結果をCSVファイルに保存 with open(csv_name, 'w', newline='', encoding='utf-8') as csvfile: fieldnames = ['Title', 'Video ID', 'URL', 'View Count', 'Subscriber Count', 'Published At'] writer = csv.DictWriter(csvfile, fieldnames=fieldnames) # CSVファイルのヘッダーを書き込む writer.writeheader() # 検索結果から情報を取得してCSVに書き込む for item in search_response['items']: title = item['snippet']['title'] video_id = item['id']['videoId'] url = f'https://www.youtube.com/watch?v={video_id}' # 動画の詳細情報を取得 video_response = youtube.videos().list( part='statistics,snippet', id=video_id ).execute() # 再生回数を取得 view_count = video_response['items'][0]['statistics']['viewCount'] # チャンネルの詳細情報を取得 channel_id = item['snippet']['channelId'] channel_response = youtube.channels().list( part='statistics', id=channel_id ).execute() # サブスクライバー数を取得 subscriber_count = channel_response['items'][0]['statistics']['subscriberCount'] # アップロード日付を取得 published_at = video_response['items'][0]['snippet']['publishedAt'] # CSVに書き込む writer.writerow({'Title': title, 'Video ID': video_id, 'URL': url, 'View Count': view_count, 'Subscriber Count': subscriber_count, 'Published At': published_at}) print("Finish work") if __name__ == '__main__': # 検索するキーワードを指定 search_keyword = keyword # 任意のキーワードを指定してください # 検索結果をCSVファイルに保存 search_youtube_videos(search_keyword)