python - 如何使用 YouTube Data API V3 获取视频的所有评论(超过 100 条)?

标签 python youtube-api youtube-data-api

我目前正在做一个项目,我需要收集几个特定 YouTube 视频的所有评论。
我最多可以使用 commentThreads().list 函数 ( More here ) 获得 100 条评论。有什么办法可以得到所有的评论吗?

我正在使用 Google YouTube 数据 API 开发人员指南提供的以下功能。

def get_comment_threads(youtube, video_id):
  results = youtube.commentThreads().list(
    part="snippet",
    maxResults=100,
    videoId=video_id,
    textFormat="plainText"
  ).execute()

  for item in results["items"]:
    comment = item["snippet"]["topLevelComment"]
    author = comment["snippet"]["authorDisplayName"]
    text = comment["snippet"]["textDisplay"]
    print "Comment by %s: %s" % (author, text)

  return results["items"]

最佳答案

如上面的评论所述,您可以简单地使用 next_page_token 并调用 while 循环,直到您停止获取下一页 token 。但请注意,有些视频有大量评论,这将需要很长时间才能加载。

另外,我写信是为了扩展您上面提到的代码。

我还从一些我现在不记得的 Github 存储库中复制了这段代码的一些部分。

更新您之前在 get_comment_threads 函数中使用的 youtubevideo_id 变量。

def load_comments(match):
    for item in match["items"]:
        comment = item["snippet"]["topLevelComment"]
        author = comment["snippet"]["authorDisplayName"]
        text = comment["snippet"]["textDisplay"]
        print("Comment by {}: {}".format(author, text))
        if 'replies' in item.keys():
            for reply in item['replies']['comments']:
                rauthor = reply['snippet']['authorDisplayName']
                rtext = reply["snippet"]["textDisplay"]
            print("\n\tReply by {}: {}".format(rauthor, rtext), "\n")

def get_comment_threads(youtube, video_id):
    results = youtube.commentThreads().list(
        part="snippet",
        maxResults=100,
        videoId=video_id,
        textFormat="plainText"
    ).execute()
    return results

video_id = ""
youtube = ""
match = get_comment_thread(youtube, video_id)
next_page_token = match["nextPageToken"]
load_comments(match)

while next_page_token:
    match = get_comment_thread(youtube, video_id)
    next_page_token = match["nextPageToken"]
    load_comments(match)

关于python - 如何使用 YouTube Data API V3 获取视频的所有评论(超过 100 条)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36585824/

相关文章:

javascript - YouTube Iframe API 初始化后,player.getPlayerState 不可用

java - 在 Android 应用程序中使用 youtube API 滚动屏幕时如何避免视频停止?

youtube-api - YouTube API : Get upload playlistID for YouTube Channel

android - 如何在 Android 后台播放 YouTube 视频?

youtube - 如何检查 YouTube channel 是否正在直播

python - Pandas crosstab() 函数与包含 NaN 值的数据框的混淆行为

python - 在python中获取第n行字符串

python - 里普利的 K 函数(二阶强度函数)Python

python - 根据 Pandas DataFrame 中的元素从另一个 DataFrame 中获取元素

youtube-api - YouTube API v3 获取与登录用户关联的所有 channel