我正在尝试使用Java程序获取YouTube视频的所有评论.我不能得到它们,因为它有"显示更多"而不是所有的评论.我正在寻找一种方法来获取我可以通过的所有评论或评论页面.我有一个视频ID和东西,只需要评论.
我尝试过all_comments而不是在网址中观看,但它仍然没有显示所有评论,并重定向再次观看.
我也查看了YouTube api,只能找到如何获取他们的ID评论,但我需要从视频ID中获取所有评论.
如果有人知道怎么做,请告诉我.
我已经为那些可以给我一个很好的答案的人增加了50个代表奖金.
您需要获取视频的评论主题列表请求,然后使用上一个响应中的下一页标记向前滚动:
private static int counter = 0;
private static YouTube youtube;
public static void main(String[] args) throws Exception {
// For Auth details consider:
// https://github.com/youtube/api-samples/blob/master/java/src/main/java/com/google/api/services/samples/youtube/cmdline/Auth.java
// Also don't forget secrets https://github.com/youtube/api-samples/blob/master/java/src/main/resources/client_secrets.json
List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/youtube.force-ssl");
Credential credential = Auth.authorize(scopes, "commentthreads");
youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, credential).build();
String videoId = "video_id";
// Get video comments threads
CommentThreadListResponse commentsPage = prepareListRequest(videoId).execute();
while (true) {
handleCommentsThreads(commentsPage.getItems());
String nextPageToken = commentsPage.getNextPageToken();
if (nextPageToken == null)
break;
// Get next page of video comments threads
commentsPage = prepareListRequest(videoId).setPageToken(nextPageToken).execute();
}
System.out.println("Total: " + counter);
}
private static YouTube.CommentThreads.List prepareListRequest(String videoId) throws Exception {
return youtube.commentThreads()
.list("snippet,replies")
.setVideoId(videoId)
.setMaxResults(100L)
.setModerationStatus("published")
.setTextFormat("plainText");
}
private static void handleCommentsThreads(List<CommentThread> commentThreads) {
for (CommentThread commentThread : commentThreads) {
List<Comment> comments = Lists.newArrayList();
comments.add(commentThread.getSnippet().getTopLevelComment());
CommentThreadReplies replies = commentThread.getReplies();
if (replies != null)
comments.addAll(replies.getComments());
System.out.println("Found " + comments.size() + " comments.");
// Do your comments logic here
counter += comments.size();
}
}
Run Code Online (Sandbox Code Playgroud)
如果您需要示例骨架项目,请考虑api-samples.
更新
您无法获得所有评论的情况也可能是由配额限制引起的(至少我遇到过):
这不是java,python,js或任何特定于语言的规则.如果您想要超过配额,则无法申请更高的配额.不过,我会从控制吞吐量开始.很容易超过100秒/用户配额.
| 归档时间: |
|
| 查看次数: |
12156 次 |
| 最近记录: |