Pythonを使用したYouTubeコメント取得におけるエラーについて

Python

1import requests 2import json 3 4URL = 'https://www.googleapis.com/youtube/v3/'5# ここにAPI KEYを入力6API_KEY = 'API KEYを入力'7# ここにVideo IDを入力8VIDEO_ID = 'Video IDを入力'9 10def print_video_comment(no, video_id, next_page_token):11 params = {12 'key': API_KEY,13 'part': 'snippet',14 'videoId': video_id,15 'order': 'relevance',16 'textFormat': 'plaintext',17 'maxResults': 100,18 }19 if next_page_token is not None:20 params['pageToken'] = next_page_token 21 response = requests.get(URL + 'commentThreads', params=params)22 resource = response.json()23 24 for comment_info in resource['items']:25 # コメント26 text = comment_info['snippet']['topLevelComment']['snippet']['textDisplay']27 # グッド数28 like_cnt = comment_info['snippet']['topLevelComment']['snippet']['likeCount']29 # 返信数30 reply_cnt = comment_info['snippet']['totalReplyCount']31 # ユーザー名32 user_name = comment_info['snippet']['topLevelComment']['snippet']['authorDisplayName']33 # Id34 parentId = comment_info['snippet']['topLevelComment']['id']35 print('{:0=4}\t{}\t{}\t{}\t{}'.format(no, text.replace('\r', '\n').replace('\n', ' '), like_cnt, user_name, reply_cnt))36 if reply_cnt > 0:37 cno = 138 print_video_reply(no, cno, video_id, None, parentId)39 no = no + 140 41 if 'nextPageToken' in resource:42 print_video_comment(no, video_id, resource["nextPageToken"])43 44def print_video_reply(no, cno, video_id, next_page_token, id):45 params = {46 'key': API_KEY,47 'part': 'snippet',48 'videoId': video_id,49 'textFormat': 'plaintext',50 'maxResults': 50,51 'parentId': id,52 }53 54 if next_page_token is not None:55 params['pageToken'] = next_page_token 56 response = requests.get(URL + 'comments', params=params)57 resource = response.json()58 59 for comment_info in resource['items']:60 # コメント61 text = comment_info['snippet']['textDisplay']62 # グッド数63 like_cnt = comment_info['snippet']['likeCount']64 # ユーザー名65 user_name = comment_info['snippet']['authorDisplayName']66 67 print('{:0=4}-{:0=3}\t{}\t{}\t{}'.format(no, cno, text.replace('\r', '\n').replace('\n', ' '), like_cnt, user_name))68 cno = cno + 169 70 if 'nextPageToken' in resource:71 print_video_reply(no, cno, video_id, resource["nextPageToken"], id)72 73# コメントを全取得する74video_id = VIDEO_ID 75no = 176print_video_comment(no, video_id, None)77

コメントを投稿

0 コメント