我一直在尝试使用 Python 从 YouTube 上的给定视频中获取评论(线程和回复)(作为学习语言的练习)。
根据官方网站(https://developers.google.com/youtube/v3/docs/commentThreads/list)上给出的示例,我能够得到一些评论,但不是全部。我尝试添加一些代码来处理多个页面,但是我无法获得只有一个页面的视频的评论。
例如,https://www.youtube.com/watch?v=Gd_L7DVKTA8有 17 条评论(包括回复),但我只能获得 7 个线程和 2 个回复。有趣的是,我使用上面链接中提供的 API Explorer 得到了相同的结果(只有 7 个线程)。
我的代码如下:
#!/usr/bin/python
# Usage:
# python scraper.py --videoid='<video_id>'
from apiclient.errors import HttpError
from oauth2client.tools import argparser
from apiclient.discovery import build
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"
DEVELOPER_KEY = 'key'
def get_comment_threads(youtube, video_id, comments):
threads = []
results = youtube.commentThreads().list(
part="snippet",
videoId=video_id,
textFormat="plainText",
).execute()
#Get the first set of comments
for item in results["items"]:
threads.append(item)
comment = item["snippet"]["topLevelComment"]
text …Run Code Online (Sandbox Code Playgroud)