YouTube数据API评论分页
我在用Python处理YouTube视频评论时遇到了一些困难,特别是在遍历所有评论的语法上。我发现关于GetYouTubeVideoCommentFeed()
这个函数的文档很少。
我真正想做的是在视频的所有评论中搜索某个词,并增加一个计数器(最后会把这个评论打印出来)。这个方法对返回的25条结果有效,但我需要访问更多的评论。
import gdata.youtube
import gdata.youtube.service
video_id = 'hMnk7lh9M3o'
yt_service = gdata.youtube.service.YouTubeService()
comment_feed = yt_service.GetYouTubeVideoCommentFeed(video_id=video_id)
for comment_entry in comment_feed.entry:
comment = comment_entry.content.text
if comment.find('hi') != -1:
counter = counter + 1
print "hi: "
print counter
我尝试在调用GetYouTubeVideoCommentFeed()
时设置start_index
和video_id
,但好像不太行。
我是不是漏掉了什么?
谢谢!
Steve
2 个回答
1
我找到了方法。你可以把视频的链接传给GetYouTubeVideoCommentFeed这个函数,而不是传视频的ID。通过修改链接里的参数,你可以浏览评论。
不过,这里可能有个API的限制;我只能查看到这个视频的最后1000条评论。
5
这里是相关的代码片段:
# Comment feed URL
comment_feed_url = "http://gdata.youtube.com/feeds/api/videos/%s/comments"
''' Get the comment feed of a video given a video_id'''
def WriteCommentFeed(video_id, data_file):
url = comment_feed_url % video_id
comment_feed = yt_service.GetYouTubeVideoCommentFeed(uri=url)
try:
while comment_feed:
for comment_entry in comment_feed.entry:
print comment_entry.id.text
print comment_entry.author[0].name.text
print comment_entry.title.text
print comment_entry.published.text
print comment_entry.updated.text
print comment_entry.content.text
comment_feed = yt_service.Query(comment_feed.GetNextLink().href)
except:
pass