LoginSignup
9
13

More than 3 years have passed since last update.

PythonでYouTubeのコメントを取得

Posted at

YouTubeのAPIを使って、動画のコメントを取得します。YouTubeのAPIについては割愛します。

やり方

getYouTubeComments.py
import requests
import json

URL = 'https://www.googleapis.com/youtube/v3/'
# ここにAPI KEYを入力
API_KEY = 'API KEYを入力'

def print_video_comment(video_id, next_page_token):
  params = {
    'key': API_KEY,
    'part': 'snippet',
    'videoId': video_id,
    'order': 'relevance',
    'textFormat': 'plaintext',
    'maxResults': 100,
  }
  if next_page_token is not None:
    params['pageToken'] = next_page_token
  response = requests.get(URL + 'commentThreads', params=params)
  resource = response.json()

  for comment_info in resource['items']:
    # コメント
    text = comment_info['snippet']['topLevelComment']['snippet']['textDisplay']
    # グッド数
    like_cnt = comment_info['snippet']['topLevelComment']['snippet']['likeCount']
    # 返信数
    reply_cnt = comment_info['snippet']['totalReplyCount']

    print('{}\t{}\t{}'.format(text.replace('\n', ' '), like_cnt, reply_cnt))

  if 'nextPageToken' in resource:
    print_video_comment(video_id, resource["nextPageToken"])

# ここにVideo IDを入力
video_id = 'Video IDを入力'
print_video_comment(video_id, None)

実行結果の例

日本相撲協会公式チャンネル「高崎親方の料理の鉄人~出羽海部屋ちゃんこ~」の動画コメントを取得すると、下記のようになります。Google Colaboratoryで実行しています。

出力結果は、コメント、グッド数、返信数の順です。

スクリーンショット 2020-09-27 23.29.45.png

参考

下記の記事を参考にしました。ありがとうございました。
- https://qiita.com/Doarakko/items/191209bf14cf5d76fa6f

9
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
13