[PYTHON] Lesen Sie alle Kommentare und Antworten zu YouTube-Videos

Ich habe versucht, alle Kommentare einschließlich der Antworten von YouTube-Videos mit Python-Skript zu erhalten

YouTube-Videokommentar unlesbares Problem

Es gibt einige YouTube-Videos, die manchmal seltsam viele Kommentare enthalten. Wenn Sie jedoch versuchen, dies in Ihrem Browser oder Ihrer App zu lesen,

Halt.

Es hört einfach auf. Selbst wenn ich nach langer Zeit mit einem PC das Feuer einschalte, stoppt der Browser perfekt.

Lesen Sie mit YouTube API / Script

In einem solchen Fall scheint es eine praktische YouTube-API zu geben, und es gibt viele Skripte, die bereits veröffentlicht wurden. Ich konnte jedoch nichts finden, das alle Kommentare erhalten könnte, und habe versucht, alle Kommentare einschließlich der Antwort abzurufen.

Skript

getComments.py



import datetime
import json
import requests

URL = 'https://www.googleapis.com/youtube/v3/'
API_KEY = 'xxx'
VIDEO_ID = 'yyy'

def get_video_comment(video_id, n):
    try:
        next_page_token
    except NameError:
        params = {
            'key': API_KEY,
            'part': 'replies, snippet',
            'videoId': VIDEO_ID,
            'order': 'time',
            'textFormat': 'plaintext',
            'maxResults': n,
        }
    else:
        params = {
            'key': API_KEY,
            'part': 'replies, snippet',
            'videoId': VIDEO_ID,
            'order': 'time',
            'textFormat': 'plaintext',
            'pageToken': next_page_token,
            'maxResults': n,
        }
    response = requests.get(URL + 'commentThreads', params=params)
    resource = response.json()
    return resource

def print_video_comment_replies(match):
    for comment_info in match['items']:
        author = comment_info['snippet']['authorDisplayName']
        pubdate = comment_info['snippet']['publishedAt']
        text = comment_info['snippet']['textDisplay']
        pubdate = datetime.datetime.strptime(pubdate, '%Y-%m-%dT%H:%M:%SZ')
        pubdate = pubdate.strftime("%Y/%m/%d %H:%M:%S")
        print('\t___________________________________________\n')
        print("\n\tReply :\n\t{}\n\n\tby: {} date: {}".format(text, author, pubdate), "\n")

def print_video_comment(match):
    global parentId
    for comment_info in match['items']:
        parentId = comment_info['id']
        author = comment_info['snippet']['topLevelComment']['snippet']['authorDisplayName']
        pubdate = comment_info['snippet']['topLevelComment']['snippet']['publishedAt']
        text = comment_info['snippet']['topLevelComment']['snippet']['textDisplay']
        like_cnt = comment_info['snippet']['topLevelComment']['snippet']['likeCount']
        reply_cnt = comment_info['snippet']['totalReplyCount']
        pubdate = datetime.datetime.strptime(pubdate, '%Y-%m-%dT%H:%M:%SZ')
        pubdate = pubdate.strftime("%Y/%m/%d %H:%M:%S")
        print('---------------------------------------------------\n')
        print('{}\n\n by: {} date: {} good: {} reply: {}\n'.format(text, author, pubdate, like_cnt, reply_cnt))
        if reply_cnt > 0:
            replyMatch = treat_reply(match)
            print_video_comment_replies(replyMatch)
            global reply_next_page_token
            try:
                reply_next_page_token = replyMatch["nextPageToken"]
            except KeyError:
                pass
            else:
                while 'reply_next_page_token' in globals():
                    replyMatch = treat_reply(match)
                    print_video_comment_replies(replyMatch)
                    try:
                        reply_next_page_token = replyMatch["nextPageToken"]
                    except KeyError:
                        reply_next_page_token = None
                        del reply_next_page_token
            reply_next_page_token = None
            del reply_next_page_token

def treat_reply(match):
    for comment_info in match['items']:
        try:
            comment_info['replies']
        except KeyError:
            pass
        else:
            try:
                reply_next_page_token
            except NameError:
                params = {
                 'key': API_KEY,
                 'part': 'id, snippet',
                 'parentId': parentId,
                 'textFormat': 'plaintext',
                 'maxResults': 100,
                 'order': 'time',
                }
            else:
                params = {
                 'key': API_KEY,
                 'part': 'id, snippet',
                 'parentId': parentId,
                 'textFormat': 'plaintext',
                 'maxResults': 100,
                 'order': 'time',
                 'pageToken': reply_next_page_token,
                }
            response = requests.get(URL + 'comments', params=params)
            resource = response.json()
            return resource


# Main

key = None

while 'key' in locals():
    match = get_video_comment(VIDEO_ID, 100)
    print_video_comment(match)
    try:
        next_page_token = match["nextPageToken"]
    except KeyError:
        next_page_token = None
        del next_page_token
        del key

Stellen Sie die Variablen API_KEY und VIDEO_ID im Skript entsprechend ein. VIDEO_ID ist die Video-URL.

Punkt

Ich mache es. Nun, wie es im Handbuch steht ...

https://developers.google.com/youtube/v3/docs/commentThreads#resource

To retrieve all of the replies for the top-level comment, you need to call the comments.list method and use the parentId request parameter to identify the comment for which you want to retrieve replies.

Ich wollte im Hauptprozess zwischen Kommentaren-> Kommentarantworten wechseln, konnte aber nur daran denken, den CommentThreads-Parameter maxResults auf 1 zu setzen, wodurch APIs für die Anzahl der Kommentare ausgegeben werden. Es wäre lächerlich (oder in einigen Fällen eher wütend genug), dies zu tun, daher hat es eine etwas unbefriedigende Struktur, die Kommentarantwortfunktion in print_video_comment () aufzurufen. Die Variable reply_next_page_token wird zwischen Funktionen wiederverwendet, daher ist eine globale Deklaration erforderlich. (Ich war süchtig danach, ohne es zuerst zu bemerken.)

Andere

Die Methode zum Überprüfen der Existenz von Variablen ist im Skript nicht einheitlich, aber keine Sorge ...

Referenz

API Reference - CommentThreads API Reference - Comments Kommentare auf Youtube in Python abrufen

Recommended Posts

Lesen Sie alle Kommentare und Antworten zu YouTube-Videos
Erhalten Sie Kommentare auf Youtube Live mit [Python] und [Pytchat]!