list() 返回视频中不同数量的评论

问题描述 投票:0回答:1

我正在尝试使用 youtube API 抓取给定 videoId 的评论。 但爬取的评论数量少于其实际数量。 你对此有什么想法吗?我的代码如下。

from googleapiclient.discovery import build
from typing import List

def get_comments(api, video_id: str, fields: str)-> List[List[str]]:
    comments = list()
    response = api.commentThreads().list(part='snippet', fields=fields, videoId=video_id, maxResults=50).execute()
    
    all_comment_crawled = True
    while all_comment_crawled:
        for item in response['items']:
            comment = item['snippet']['topLevelComment']['snippet']
            comments.append([comment['textOriginal'], comment['likeCount']])

        if 'nextPageToken' in response:
            response = api.commentThreads().list(part='snippet', videoId=video_id, fields=fields, pageToken=response['nextPageToken'], maxResults=50).execute()
        else:
            all_comment_crawled = False
         
    return comments

api_key = "MY_API_KEY"
api_obj = build('youtube', 'v3', developerKey=api_key)

video_id = 'fgSvGLxanCo'
fields = 'items(snippet(totalReplyCount, topLevelComment(snippet(textOriginal, likeCount)))), nextPageToken'

comments = get_comments(api_obj, video_id, fields)
print(len(comments)) # returns 1,945 actually is over 2,000
youtube-api youtube-data-api youtube-livestreaming-api
1个回答
2
投票

在 YouTube 视频上列出评论时有一个陷阱(我宣布另一个很容易陷入的陷阱):

  1. YouTube 上的评论计数统计所有(未过滤的)评论。 回复包含在此计数中,并且您尚未在算法中考虑它们。看看CommentThreads:列表
  2. 使用commentThreads时的回复给出最多5个回复。 如果该消息有超过 5 个回复,您必须使用评论:列表列出所有回复。

这里有一个处理视频所有评论的 Python 脚本示例。

© www.soinside.com 2019 - 2024. All rights reserved.