import os from googleapiclient.discovery import build def search_youtube(keyword, max_results=5): """ 指定したキーワードでYouTube動画を検索し、結果を表示する """ # 1. APIの設定(ここに取得したAPIキーを入力してください) API_KEY = 'YOUR_API_KEY_HERE' # APIクライアントの作成 youtube = build('youtube', 'v3', developerKey=API_KEY) try: # 2. 検索リクエストの実行 request = youtube.search().list( q=keyword, part='snippet', maxResults=max_results, type='video', order='relevance' # 関連度順(viewCountにすれば再生数順) ) response = request.execute() # 3. 結果の出力 print(f"--- '{keyword}' の検索結果 ---") for item in response.get('items', []): title = item['snippet']['title'] video_id = item['id']['videoId'] channel_title = item['snippet']['channelTitle'] video_url = f"https://www.youtube.com/watch?v={video_id}" print(f"タイトル: {title}") print(f"チャンネル名: {channel_title}") print(f"URL: {video_url}") print("-" * 30) except Exception as e: print(f"エラーが発生しました: {e}") if __name__ == "__main__": # 実行部分 search_word = input("検索したいキーワードを入力してください: ") search_youtube(search_word)