いくつかの参考動画にしたがって、PythonでYouTube Data API v3のSearch:Listをテスト実行させた際のメモ書きを共有します。
目次:

PythonでYouTube Data API v3のSearch:List操作する際に参考にした動画
参考にした動画はこちら。
YouTube API を使って YouTube をマーケティング的に活用。本動画では 2016年 1月から 2019年10月までの "Kotlin" の各月アップロード数を抽出。そして CSV に自動保存。
YouTube Data APIドキュメント上でのテスト実行
YouTube Data API のドキュメント内からテストが可能です。
Search > list のテスト (ページ最下部)からテスト実行。
q の項目に任意のキーワードを入れると、キーワード検索結果データが返ってきます。
下の画像では q = 'kotlin' と入力してテスト実行した結果。
パラメータ: q について
The q parameter specifies the query term to search for.
コーディング
APIキーの取得等については を参照。
利用するAPIは YouTube Data API v3 でOK。
from googleapiclient.discovery import build # ライブラリのインポート
api_key = 'AIxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx4' # 自分のAPIキーを格納
youtube = build('youtube', 'v3', developerKey=api_key) # build関数を実行、変数に格納
request_kotlin = my_youtube.search().list(
# 下記、検索条件(フィルタ)
q = 'kotlin',
part = 'snippet',
type = 'video', # channel, playlist, video
videoCategoryId = '27', # 27:Education
publishedAfter = "2016-01-01T00:00:00Z", # から(from)
publishedBefore = "2019-11-01T00:00:00Z" # まで(to)
)
VideoCategories | YouTube DataAPI
VideoCategoryId : youtube api video category id list
response_kotlin = request_kotlin.execute() #リクエストを実行してレスポンスとして格納
JSON形式のデータが返ってくる
{'kind': 'youtube#searchListResponse',
'etag': '9AyvSwl2YXCj5CcutjU3QmufH5s',
'nextPageToken': 'CAUQAA',
'regionCode': 'JP',
'pageInfo': {'totalResults': 340639, 'resultsPerPage': 5},
'items': [{'kind': 'youtube#searchResult',
'etag': '3ICQIG2qiapFXElgQWKNqju7egQ',
'id': {'kind': 'youtube#video', 'videoId': 'F9UC9DY-vIU'},
'snippet': {'publishedAt': '2019-07-12T13:11:25Z',
'channelId': 'UC8butISFwT-Wl7EV0hUK0BQ',
'title': 'Kotlin Course - Tutorial for Beginners',
'description': 'Learn the Kotlin programming language in this introduction to Kotlin. Kotlin is a general purpose, open source, statically typed “pragmatic” programming ...',
'thumbnails': {'default': {'url': 'https://i.ytimg.com/vi/F9UC9DY-vIU/default.jpg',
'width': 120,
'height': 90},
'medium': {'url': 'https://i.ytimg.com/vi/F9UC9DY-vIU/mqdefault.jpg',
'width': 320,
'height': 180},
'high': {'url': 'https://i.ytimg.com/vi/F9UC9DY-vIU/hqdefault.jpg',
'width': 480,
'height': 360}},
'channelTitle': 'freeCodeCamp.org',
'liveBroadcastContent': 'none',
'publishTime': '2019-07-12T13:11:25Z'}},
{'kind': 'youtube#searchResult',
show more (open the raw output data in a text editor) ...
'high': {'url': 'https://i.ytimg.com/vi/7WVLyowTEZg/hqdefault.jpg',
'width': 480,
'height': 360}},
'channelTitle': 'edureka!',
'liveBroadcastContent': 'none',
'publishTime': '2019-08-01T14:10:28Z'}}]}
JSON形式 = 辞書型のため、キーを指定して値を取り出すことが出来る。
例: kotlinで検索した場合にヒットした検索結果総数だけを取り出したい時
response_kotlin['pageInfo']['totalResults'] // 340639
月ごとに動画がアップロードされている本数を調べる
日付をループさせる
year = ['2016', '2017', '2018', '2019']
month = []
for i in range(1, 13):
if 0 < i < 10:
month.append('0' + str(i))
else:
month.append(str(i))
あとはソースコードと動画を参照
# Kotlin
def my_function():
request_kotlin = my_youtube.search().list( q="kotlin", part="snippet", type="video", videoCategoryId="27",publishedAfter=my_publishedAfter, publishedBefore=my_publishedBefore)
response_kotlin = request_kotlin.execute()
kotlin_youtube = response_kotlin["pageInfo"]["totalResults"]
print(response_kotlin)
print("Kotlin: " + str(kotlin_youtube))
with open('YouTubeAPI_Kotlin.csv', 'a') as csvFile:
writer = csv.writer(csvFile)
writer.writerow([str(y), str(i), str(kotlin_youtube)])
csvFile.close()
import csv
for y in year:
i = 0
while i < 12:
if i == 11:
i = i + 1
my_publishedAfter = str(y) + "-12-01T00:00:00Z"
yy = int(y) + 1
my_publishedBefore = str(yy) + "-01-01T00:00:00Z"
my_function()
break
else:
# from "my_publishedAfter" to "my_publishedBefore"
after_month = month[i]
i = i + 1
before_month = month[i]
my_publishedAfter = y + "-" + after_month + "-01T00:00:00Z"
my_publishedBefore = y + "-" + before_month + "-01T00:00:00Z"
my_function()
この記事の気になった箇所を読み返す:
Category:
Tags: