webmaster-kazu.com

テクノロジー・データ分析・実践ログ・その他

YouTube Data API v3を使ってPythonでYouTube検索結果のデータを取得する

カテゴリ: API

YouTube Data APIを導入してみるという記事を公開しましたが、YouTube Data APIのAPIキーを取得しましたので、PythonでYouTubeのデータを取得してみます。(Windows10)

参考:https://developers.google.com/youtube/v3/code_samples/python?hl=ja

■Python

Pythonバージョン

今回のPythonのバージョンは、「3.8.2」を使用しています。

Google API Clientをインストールする

PythonでYoutueのデータを取得する前に、PythonにGoogle API Clientをインストールします。

pip install google-api-python-client

コマンドプロンプトから上記のコードを記述し、ENTERキーを押します。

ENTERキーを押すと、パッケージが確認され、インストールが開始されます。

Successfully installed google-api-core-1.20.0 google-api-python-client-1.9.2 google-auth-1.16.1 google-auth-httplib2-0.0.3 httplib2-0.18.1 uritemplate-3.0.1

Successfully installed(正常にインストールされました)と表示されればインストールは完了となります。

oauth2clientもインストールする

pip install oauth2client

コマンドプロンプトから上記のコードを記述し、ENTERキーを押します。

Successfully installed oauth2client-4.1.3

Successfully installed(正常にインストールされました)と表示されればインストールは完了となります。

■指定したキーワードでYouTubeの検索結果の情報を取得してみる

指定したキーワードでYouTubeの検索結果の情報を取得してみます。コードサンプルはこちらのものを使います。

■コード

#!/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 = "REPLACE_ME"

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="Google")

argparser.add_argument("--max-results", help="Max results", default=25)

args = argparser.parse_args()

try:

youtube_search(args)

except HttpError, e:

print "An HTTP error %d occurred:\n%s" % (e.resp.status, e.content)

このままVisual Studio Codeなどで新規ファイルを作成して貼り付けても実行できません。

print "Channels:\n", "\n".join(channels), "\n"

print "An HTTP error %d occurred:\n%s" % (e.resp.status, e.content)

上記のコードには、print関数で出力する際の「()」がなく、「invalid syntax (<unknown>, line 45)」のエラーが発生し、プログラムが実行されないので、修正しなければいけません。

また、

DEVELOPER_KEY = "REPLACE_ME"

上記のDEVELOPER_KEYでは、"REPLACE_ME"のところに、「YouTube Data API v3」に登録した際に発行されたAPIキーを記述します。

修正後のコード

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 = "自分の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=25)

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))

若干の修正したものが上記のコードです。「argparser.add_argument("--q", help="Search term", default="検索したいキーワード")」の部分には検索したいキーワードを記述します。今回は「遊戯王」とテストで記述してみます。

■実行

修正したコードを「googleapiclient-test.py」というファイル名で保存し、コマンドプロンプトから実行してみます。

Videos:

【遊戯王】初期の最強デッキ【エクゾディア】を解説! (LLq6TwzYzaQ)

【遊戯王】20,000円絶版くじ「青眼伝説」リベンジで11万円分大勝負!!!!!! (g0KuqHPpiw0)

【遊戯王ADS】コイントスで超バーン!時の魔導師【ゆっくり実況】 (dyfkLT4VrtY)

【#遊戯王】ストラク新規で安定性アップ!!『ザンギュラのスーパーウリアッ上~2020』紹介対戦 (7Iv2N1_dluA)

【遊戯王】過激すぎて修正!?その結果、謎なことになってる闇のプレイヤーキラー戦【雑談】 (DPclpDkIYao)

【遊戯王】 まだいける…? 2020年7月改訂予想 【ゆっくり解説】 (yq2P0X2Zp6E)

【遊戯王ADS】アーク・リベリオン・エクシーズ・ドラゴン搭載型幻影騎士団【ゆっくり解説】 (op-9MvhkBs4)

【KC1st突破!!】天才ギミック搭載の岩石デッキ強すぎワロタ【遊戯王デュエルリンクス 実況No.955.5】【Yu-Gi-Oh! Duel Links】 (7RqeovmGVOM)

【#遊戯王】三体融合決戦!殲滅のサイバーエンド vs 撃滅のブルーアイズ【#博多どんよく】#64 (zGHKSFazc-Q)

【ゆっくり解説】普通の人なら一生行かない魔境。カードショップの実態について【遊戯王】 (eHgurcM175Y)

【#遊戯王】岩石リバース vs 令和ゴッドファイブ【城下町デュエル】 (9M0o2idemKQ)

【遊戯王】RRファン必見!新規の来たRRはどんな動きになるのか!?レイド・ラプターズ新展開・盤面紹介!! (fnNTHKxPVFk)

【遊戯王】瞬殺完売!!今、話題の「謎の箱」買ってみた!!!!! (rU1YQq-MuIU)

【遊戯王】見つけたら絶対買うべきBOX。 (MjT0mPrE07w)

【遊戯王】RR(レイド・ラプターズ)と幻影騎士団(ファントム・ナイツ)の強化カードが強くて月光新規でもあった~PHANTOM RAGE(フ ァントム・レイジ)収録新規カードの効果解説~ (4sHgsPWrv8A)

遊戯王#24 || 伝説のブラックパラディン! 憎しみに火をつけろ!Legendary Black Paladin! Set hatred on fire! ! Yugioh 2020 (k7G6WARkIjw)

【遊戯王】新弾「冥闇の決闘者」大量購入でラーの翼神竜ホロ狙ってみた!!!!! (ZiPhWHvHcG0)

遊戯王!次元のダークサイド|武藤優希vs海馬瀬戸 (Tqt0_dNIOv0)

【遊戯王タッグフォース6】猿でも分かる簡単害悪デッキの回し方【ましろ/にじさんじ】 (9oo3iasaKYI)

【#遊戯王】大人気テーマ「閃刀姫」のストーリーを紹介! (AmxwJC1PqCw)

[遊戯王] ODINの開封動画 その619 ~アジア版 混沌の三幻魔開封~ (CC6imMpXKSk)

【#遊戯王】倒せるかッ!神をッ!!新規カードで最高神覚醒!!ブラックマジシャン vs ラーの翼神竜【#博多どんよく】#63 (dxLE3dsH6HI)

【遊戯王】カードショップの在庫パックを開封していく!③ Yugioh Booster pack opening Extravaganza!! 2020 #3 (F_0IMo1_tPo)

【遊戯王】超強化『機皇』VS『レッド・デーモン』次のターンなんてないんですよ...【対戦動画】/ #カードラボ サテライトショップチャンネル (zsyK-8w2Bms)

【#遊戯王】この世でポータン使ってるの俺だけ説【垂流しフリー対戦】【#ミソのデュエルのミソ】 (BNvIF87UFDU)

Channels:

Playlists:

実行してみると、「遊戯王」という指定したキーワードでYouTubeの検索結果の情報を取得することができました。