从youtube上检索评论会导致不确定性行为

2024-10-03 23:19:59 发布

您现在位置:Python中文网/ 问答频道 /正文

目前我正在尝试用python检索youtube视频的所有评论。我使用下面的代码来获取注释

#!/usr/bin/env python
import time
from gdata.youtube import service
import xmltodict

def comments_generator(client, video_id):
    baseUrl="http://gdata.youtube.com/feeds/api/videos/%s/comments?orderby=published&max-results=50" %video_id
    comment_feed = client.GetYouTubeVideoCommentFeed(baseUrl)
    while comment_feed is not None:
        for comment in comment_feed.entry:
            yield comment
        next_link = comment_feed.GetNextLink()
        if next_link is None:
            comment_feed = None
        else:
            try:
                comment_feed = client.GetYouTubeVideoCommentFeed(next_link.href)
            except:
                print "Something went wrong. Couldn't follow next link"
                comment_feed = None

client = service.YouTubeService()
commentNumber=0
for comment in comments_generator(client, "Ci0HsPELE2o"):
        commentNumber+=1
        dictVersion=xmltodict.parse(str(comment))
        replyCount = str(dictVersion["ns0:entry"]["ns1:replyCount"])
        author_name = comment.author[0].name.text
        date = comment.published
        text = comment.content.text
        publishTime = date.text.split("T")[0]
        print "Comment #%s %s" %(commentNumber,date.text)
        print("{}: {}".format(author_name, text))
        print "Reply-Count: %s" %replyCount
        print "\n"

这是这个thread中答案的改进/调整版本。在

原则上它是有效的,但存在一些非确定性行为。 当我试图检索一些Youtube视频的所有评论时,我会不时得到不同数量的评论,尽管在浏览器中打开视频时,评论的数量没有改变。在

然后我进一步调查发现,在按时间顺序排列的列表中,有些评论有时会丢失,有时甚至不会,在所有尝试中似乎都是相同的几个评论,但数量不同。这对于一些特定的youtube视频来说是正确的,但显然不是所有的。 对于某些视频,评论数量在4000条评论中最多有100条不等。在

这种非确定性行为的一个例子是ID为Ci0HsPELE2o

预期的行为是,我得到30条真正的评论(没有回复),有时我得到每一条评论,但是当我在大约1小时后尝试同一个程序时,一条评论丢失了,大多数时候是这个:

^{pr2}$

我什么都试过了,但没有发现这个问题有任何系统性,因此无法解决它。在

感谢任何帮助。在

编辑:增加了再现问题的实例


Tags: textimportclientnone数量视频youtubefeed