こんにちは、ミナピピン(@python_mllover)です。今回はyoutubeのAPIをpythonで叩いて色んな情報を取得したいと思います。
Contents
YoutubeのAPI鍵を作成する
まずYoutubeのAPI鍵を取得するのですが、ちょっとややこしいです。(自分はここで少しハマりました)
というのもYoutubeはGoogleのサービスで、基本的にすべてのGoogle系APIは、Google Developer Consoleというツールで集約管理されるように仕様変更されています。
まずは下記にアクセスしましょう。Googleアカウントを作っていない方は新規作成する必要があります。YoutubeやGMailのアカウントで利用できます。
⇒ https://console.developers.google.com/
左タブの「APIと認証」→「API」⇒「ライブラリ」とクリックし、APIライブラリの検索ボックスに「youtube」と入力すると「Youtube Data API V3」(2021年時点)というのが出てくるのでこれをクリックします。
すると「APIを有効にする」というボタンがあるのでこれをクリックします。クリックすると「my first project」というのが自動的に作成され、Youtube Data APIのデータ使用に移動します。
ここでページ上部に認証情報を作成というタブがあるので、それをクリックし認証情報を以下のように設定します。

そして、必要な認証情報をクリックすると、API鍵が出力され「完了」を押して終了です。
これで「APIとサービス」の認証情報にYoutubeのAPI鍵が追加されているので、鍵のラベルを分かりやすいようにYoutubeとでも変えておきましょう。これでAPI鍵の作成は完了です。

これでAPI鍵が作成できたので、次からPythonを使ってYoutubeのAPIを叩いていきます。
PythonでYoutubeのAPIを叩く
まず必要なライブラリをインストールします。
# ライブラリをインストール $ pip install google-api-python-client
キーワードの検索結果を取得
from apiclient.discovery import build
YOUTUBE_API_KEY = '自分のAPI鍵'
youtube = build('youtube', 'v3', developerKey=YOUTUBE_API_KEY)
search_response = youtube.search().list(
part='snippet',
# 検索したい文字列
q='ホロライブ',
# 検索条件(今回は視聴回数が多い順に取得)
order='viewCount',
# 検索対象(今回は動画に絞る)
type='video',
).execute()
print(search_response)
APIの戻り値はdict型になっています。search_response['items']と打つと検索結果を辞書型のデータがリスト型に格納された形式で取得できます。

検索結果を100件以上取得する
今のままだと5件しか取得できていないので、繰り返すことで100件まで取得できます。
def get_video_info(part, q, order, type, num):
dic_list = []
search_response = youtube.search().list(part=part,q=q,order=order,type=type)
output = youtube.search().list(part=part,q=q,order=order,type=type).execute()
#一度に5件しか取得できないため何度も繰り返して実行
for i in range(num):
dic_list = dic_list + output['items']
search_response = youtube.search().list_next(search_response, output)
output = search_response.execute()
df = pd.DataFrame(dic_list)
#各動画毎に一意のvideoIdを取得
df1 = pd.DataFrame(list(df['id']))['videoId']
#各動画毎に一意のvideoIdを取得必要な動画情報だけ取得
df2 = pd.DataFrame(list(df['snippet']))[['channelTitle','publishedAt','channelId','title','description']]
ddf = pd.concat([df1,df2], axis = 1)
return ddf
参照:https://qiita.com/g-k/items/7c98efe21257afac70e9
定義した関数を実行してみます。引数のnum×5の検索件数を取得できます。
df = get_video_info(part='snippet', q='dbd', order='viewCount', type='video', num = 30) df
<実行結果>

見てもらえば分かりますが、再生回数は一緒に返ってこないので、再生回数はここからvideoIdを取得して再度別のAPIを叩いて取得する必要があります。
再生回数を取得
# 動画情報を取得する
for vdata in search_response['items']:
id_ = vdata['id']['videoId']
statistics = youtube.videos().list(part = 'statistics', id = id_).execute()['items'][0]['statistics']
print('動画タイトル',vdata['snippet']['title'])
print('投稿者名:',vdata['snippet']['channelTitle'])
print('再生回数:',statistics['viewCount'],'高評価数:',statistics['likeCount'],'低評価数:',statistics['dislikeCount'],'コメント数:',statistics['commentCount'])
print('------------------------------------------------------------')
チャンネルごとの投稿動画情報を取得
# hololive ホロライブ - VTuber GroupのチャンネルID
cId = 'UCJFZiqLMntJufDCHc6bQixg'
# 動画情報を取得
response = youtube.search().list(
# 検索部分を指定
part = "snippet",
# チャンネルID
channelId = cId,
# 検索数
maxResults = 10,
# 検索順(今回は日付)
order = "date"
).execute()
for vdata in response['items']:
count_data = youtube.videos().list(part = 'statistics', id = vdata['id']['videoId']).execute()['items'][0]['statistics']
print('投稿日:',vdata['snippet']['publishedAt'])
print('動画名:',vdata['snippet']['title'])
print('再生回数:',count_data['viewCount'],'高評価数:',count_data['likeCount'],'低評価数:',count_data['dislikeCount'],)
print('-----------------------------------------------------------------')
チャンネル情報(登録者数・総再生回数)を取得
# hololive ホロライブ - VTuber GroupのチャンネルID
cId = 'UCJFZiqLMntJufDCHc6bQixg'
search_response = youtube.channels().list(
part='snippet,statistics',
id=cId,
).execute()
print('登録者数:',search_response['items'][0]['statistics']['subscriberCount'],'人')
print('投稿動画数:',search_response['items'][0]['statistics']['videoCount'],'本')
print('総再生数:',search_response['items'][0]['statistics']['viewCount'],'回')
取得した情報をcsv出力(おまけ)
import pandas as pd
# hololive ホロライブ - VTuber GroupのチャンネルID
cId = 'UCJFZiqLMntJufDCHc6bQixg'
# 動画情報を取得
response = youtube.search().list(
# 検索部分を指定
part = "snippet",
# チャンネルID
channelId = cId,
# 検索数
maxResults = 10,
# 検索順(今回は日付)
order = "date" ).execute()
data = []
for vdata in response['items']:
count_data = youtube.videos().list(
part = 'statistics',
id = vdata['id']['videoId']
).execute()['items'][0]['statistics']
pub_date = vdata['snippet']['publishedAt']
v_title = vdata['snippet']['title']
v_count = int(count_data['viewCount'])
v_like = int(count_data['likeCount'])
v_dislike = int(count_data['dislikeCount'])
data.append([pub_date,v_title,v_count,v_like,v_dislike])
data = pd.DataFrame(data,columns=['date','title','count','like','dislike'])
data.to_csv('youtube.csv')
終わり
このAPI使ってなんかサービス作れないかなと思案中、結局プログラミングで儲けるにはプログラミング力よりアイデア力ですね(笑
参照記事:【Python】TwitterのAPIを使って特定のアカウントの呟きを一括取得する
参照記事:【Python】ニコニコ動画のAPIを使って動画情報を取得する
参照記事:【Web技術】APIについて実用例を踏まえて分かりやすく解説してみる


コメント
[…] 関連記事:【Python】YoutubeのAPIを叩いて色んな動画情報を取得してみる […]
[…] 関連記事:【Python】YoutubeのAPIを叩いて色んな動画情報を取得してみる […]
[…] 関連記事:【Python】YoutubeのAPIを叩いて検索結果と各動画の再生回数を取得する […]
[…] 【Python】YoutubeのAPIを叩いて検索結果と各動画の再生回数を取得する […]
[…] 関連動画:YoutubeのAPIを使って動画再生回数などをスクレイピングする […]