🐍

Python を使ってYoutubeのデータを取得する

2021/03/08に公開

YouTube Data APIを使おう

なんか1年くらい前にYoutubeAPIを使った時のコードを見つけたので、記録として、、

準備

  1. Youtube Data APIの登録
  2. ライブラリのインストール

1. Youtube Data APIの登録

公式ガイド
リンク先の「作業を始める前に」を参考に、、、
apikeyをコピーしておく

2. ライブラリのインストール

pip install google-api-python-client

検索結果の取得

from apiclient.discovery import build
YOUTUBE_API_KEY = 'YOURAPIKEY'
youtube = build('youtube', 'v3', developerKey=YOUTUBE_API_KEY)

# 検索したい文字列
search_word = '東海オンエア'

res = youtube.search().list(
    part='snippet',
    q=search_word,
    #視聴回数が多い順に取得
    order='viewCount',
    type='video',).execute()

JSON形式で動画情報を取得

# 中身を見てみる
res['item']
{'kind': 'youtube#searchListResponse',
 'etag': 'ktEsVa2MibTtM9F6ZboIDNyc5Bc',
 'nextPageToken': 'CAUQAA',
 'regionCode': 'JP',
 'pageInfo': {'totalResults': 464829, 'resultsPerPage': 5},
 'items': [{'kind': 'youtube#searchResult',
   'etag': 'ofDFkqYHvfnDKFmeOSfQEi7-gp4',
   'id': {'kind': 'youtube#video', 'videoId': 'MrNzLkFwz9o'},
   'snippet': {'publishedAt': '2017-02-25T10:23:42Z',
    'channelId': 'UCutJqz56653xV2wwSvut_hQ',
    'title': '【宅配vs手作り料理】スピード対決でまさかの結果に!!!',
    'description': 'ちなみにぼくたちはガスト大好きマンなのでゆめゆめ誤解のなきよう。将来隠居したら宅配サービスはじめます。 どうも、東海オンエアです。 ぜひチャンネル登録お願いします ...',
    'thumbnails': {'default': {'url': 'https://i.ytimg.com/vi/MrNzLkFwz9o/default.jpg',
      'width': 120,
      'height': 90},
     'medium': {'url': 'https://i.ytimg.com/vi/MrNzLkFwz9o/mqdefault.jpg',
      'width': 320,
      'height': 180},
     'high': {'url': 'https://i.ytimg.com/vi/MrNzLkFwz9o/hqdefault.jpg',
      'width': 480,
      'height': 360}},
    'channelTitle': '東海オンエア',
    'liveBroadcastContent': 'none',
    'publishTime': '2017-02-25T10:23:42Z'}},

再生回数などの情報はまた別の方法でとる必要がある

Discussion