PythonでYoutube動画検索
以下を参照。
Google API Python Clientを使ってYouTube Data APIv3をいじる - Qiita
APIを許可する
Google Cloud Platformにアクセスして,新しいプロジェクトを作成。
Youtube Data APIを入れる。
YouTube Data API の概要 | YouTube Data API (v3) | Google Developers
パッケージ導入
ここを元にYoutubeに関するAPIのパッケージを導入。
Installation | API Client Library for Python | Google Developers
pip install --upgrade google-api-python-client
管理者権限で実行することを忘れずに。
サンプルコード
サンプルコードはこちらから。
Python コード サンプル | YouTube Data API (v3) | Google Developers
使ったのはYoutube検索API。なんとなく構造がわかったのでそれでよし。
適当なキーワードを入れて動画を検索し,その結果を表示。
動画とプレイリスト,チャンネルを区別できる。
APIのKEYを含めることを忘れずに。
# -*- coding: utf-8 -*- """ Created on Sun Jan 21 23:38:58 2018 @author: Edwin Ri """ #!/usr/bin/python from apiclient.discovery import build from apiclient.errors import HttpError from oauth2client.tools import argparser # Set DEVELOPER_KEY to the API key value from the APIs & auth > Registered apps # tab of # https://cloud.google.com/console # Please ensure that you have enabled the YouTube Data API for your project. DEVELOPER_KEY = "ここのKeyは最初に取得したAPIキーを用いること。" YOUTUBE_API_SERVICE_NAME = "youtube" YOUTUBE_API_VERSION = "v3" def youtube_search(options): youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, developerKey=DEVELOPER_KEY) # Call the search.list method to retrieve results matching the specified # query term. search_response = youtube.search().list( q=options.q, part="id,snippet", maxResults=options.max_results ).execute() videos = [] channels = [] playlists = [] # Add each result to the appropriate list, and then display the lists of # matching videos, channels, and playlists. for search_result in search_response.get("items", []): if search_result["id"]["kind"] == "youtube#video": videos.append("%s (%s)" % (search_result["snippet"]["title"], search_result["id"]["videoId"])) elif search_result["id"]["kind"] == "youtube#channel": channels.append("%s (%s)" % (search_result["snippet"]["title"], search_result["id"]["channelId"])) elif search_result["id"]["kind"] == "youtube#playlist": playlists.append("%s (%s)" % (search_result["snippet"]["title"], search_result["id"]["playlistId"])) print("Videos:\n", "\n".join(videos), "\n") print("Channels:\n", "\n".join(channels), "\n") print("Playlists:\n", "\n".join(playlists), "\n") if __name__ == "__main__": # 検索ワード argparser.add_argument("--q", help="Search term", default="ベートーベン") # 検索上限 argparser.add_argument("--max-results", help="Max results", default=10) args = argparser.parse_args() try: youtube_search(args) except HttpError as e: print("An HTTP error %d occurred:\n%s" % (e.resp.status, e.content))
結果はこんな感じ。
Videos: ベートーベン メドレー 長時間 BGM No.1 (JdjNRU9QtnQ) ベートーベン ピアノソナタ メドレー (Uuws9GxHnpQ) ベートーベン作曲 交響曲第6番「田園」 (DZJHWkk0x7I) ベートーベン『運命』交響曲第五番第一楽章 (PTr1v1ksWkQ) The Best of Beethoven (W-fFHeTX70Q) ベートーヴェン 交響曲第七番 小澤征爾 1975ライブ (tbVsJcX8V5w) ベートーベン・ピアノ協奏曲第5番「皇帝」 (o5fNRKUOsco) Beethoven 9 - Chicago Symphony Orchestra - Riccardo Muti (rOjHhS5MtvA) 【作業用BGM】 ベートーヴェン 名曲ピアノメドレー 13曲 (mE0WsSxB-T0) Symphony No. 9 ~ Beethoven (t3217H8JppI) Beethoven: Symphony No. 7 - Royal Concertgebouw Orchestra & Iván Fischer (-4788Tmz9Zo) Beethoven - Moonlight Sonata (FULL) (4Tr0otuiQuU) Beethoven: Symphony No.6, "Pastorale"; Jarvi, DKB (iQGm0H9l9I4) ベートーヴェン「月光」 Beethoven "Moonlight Sonata" (-uVmGm9yiGg) Beethoven "Moonlight" Sonata op 27 # 2 Mov 3 Valentina Lisitsa (zucBfXpCA6s) ベートーヴェン 歓喜の歌 交響曲第九番 Beethoven Symphony No 9-video part1- (SKWm4SWzDjg) Beethoven: Symphony No.2; Jarvi, DKB (VAnjfp7vUvA) ベートーベン 月光ソナタ 全楽章 (xOMetY6Y-AA) Beethoven Pathetique Sonata - 2nd mov 「悲愴」2楽章 Eric Heidsieck (bE2Zok2eL1Q) ベートーヴェン 第9 合唱 『歓喜の歌』訳詞付 Choral "Ode to Joy" Beethoven (iU5av55T2Yk) ベートーヴェン:交響曲 第6番 「田園」 ワルター/コロンビア響 Beethoven Symphony No.6 (byayR-OnN3U) Beethoven: Symphony no. 3 Eroica - Philippe Herreweghe - Full concert in HD (kwRVR-TmKYw) ベートーヴェン ピアノ・ソナタ 第8番 「悲愴」 バックハウス Beethoven: Piano Sonata No.8〈Patheyique〉 (-JpkaNWdJDA) Wilhelm Kempff plays Beethoven's Moonlight Sonata mvt. 3 (oqSulR9Fymg) ベートーベン - トルコ行進曲 (SexvTXYNcjY) Channels: Playlists:
もう少し詳細な説明
Search | YouTube Data API | Google Developers
メソッドが返すのは次のようなJSONで表されるデータ形式。
{ "kind": "youtube#searchResult", "etag": etag, "id": { "kind": string, "videoId": string, "channelId": string, "playlistId": string }, "snippet": { "publishedAt": datetime, "channelId": string, "title": string, "description": string, "thumbnails": { (key): { "url": string, "width": unsigned integer, "height": unsigned integer } }, "channelTitle": string } }
ちょっと使ってみたんですけどいろいろ勉強すべきことが多くて面倒っぽいなぁ