我目前正在做一个项目,我需要收集几个特定 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
函数中使用的 youtube
和 video_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/