【问题标题】:How to get all comments (more than 100) of a video using YouTube Data API V3?如何使用 YouTube Data API V3 获取视频的所有评论(超过 100 条)?
【发布时间】:2016-08-03 19:21:50
【问题描述】:

我目前正在做一个项目,我需要收集一些特定 youtube 视频的所有 cmets。
我可以使用 commentThreads().list 函数 (More here) 获得最多 100 个 cmets。有没有办法得到所有的 cmets ?

我正在使用 Google YouTube Data 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"]

标签: python youtube-api youtube-data-api


【解决方案1】:

如上面的 cmets 所述,您可以简单地使用 next_page_token 并调用 while 循环,直到您停止获取下一页令牌。但请注意,某些视频的 cmets 数量非常多,加载时间会很长。

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

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

更新 youtubevideo_id 变量,就像您之前在 get_comment_threads 函数中使用它们一样。

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)

【讨论】:

    【解决方案2】:

    要添加到@minhaj 的答案,

    while 循环将一直运行到最后一个commentThreads.list() 响应,但是最后一个响应没有nextPageToken 键并且会抛出一个键错误。

    一个简单的尝试,除了解决这个问题:

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

    【讨论】:

    • 最后一个响应的 nextPageToken 为 None 因此避免异常处理是安全的。
    猜你喜欢
    • 2021-04-22
    • 1970-01-01
    • 2019-07-27
    • 2018-07-05
    • 2021-05-07
    • 2016-04-08
    • 2013-11-26
    • 2021-03-13
    • 1970-01-01
    相关资源
    最近更新 更多