如何使用Python的gdata模块获取所有YouTube评论?

2024-05-14 17:31:28 发布

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

希望从给定的视频中获取所有评论,而不是一次浏览一页。

from gdata import youtube as yt
from gdata.youtube import service as yts

client = yts.YouTubeService()
client.ClientLogin(username, pwd) #the pwd might need to be application specific fyi

comments = client.GetYouTubeVideoComments(video_id='the_id')
a_comment = comments.entry[0]

上面的代码允许您抓取一个注释,可能是最近的注释,但是我正在寻找一种方法来同时抓取所有的注释。对于Python的gdata模块,这可能吗?


Youtube API文档用于comments、注释提要docs和Python API docs


Tags: thefromimportclientapiiddocs视频
2条回答

目前我只有一个解决方案,但它没有使用API,而且当有几千条评论时会变慢。

import bs4, re, urllib2
#grab the page source for vide
data = urllib2.urlopen(r'http://www.youtube.com/all_comments?v=video_id') #example XhFtHW4YB7M
#pull out comments
soup = bs4.BeautifulSoup(data)
cmnts = soup.findAll(attrs={'class': 'comment yt-tile-default'})
#do something with them, ie count them
print len(cmnts)

请注意,由于“class”是内置的python名称,因此无法通过regex或lambdas对“startwith”进行常规搜索,如here所示,因为您使用的是dict,而不是常规参数。由于BeautifulSoup,它也变得相当慢,但它需要使用,因为etreeminidom由于某种原因找不到匹配的标记。即使在prettyfying()bs4之后

以下是您使用Python YouTube API所要求的:

from gdata.youtube import service

USERNAME = 'username@gmail.com'
PASSWORD = 'a_very_long_password'
VIDEO_ID = 'wf_IIbT8HGk'

def comments_generator(client, video_id):
    comment_feed = client.GetYouTubeVideoCommentFeed(video_id=video_id)
    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:
             comment_feed = client.GetYouTubeVideoCommentFeed(next_link.href)

client = service.YouTubeService()
client.ClientLogin(USERNAME, PASSWORD)

for comment in comments_generator(client, VIDEO_ID):
    author_name = comment.author[0].name.text
    text = comment.content.text
    print("{}: {}".format(author_name, text))

不幸的是,API将可检索的条目数限制为1000。这是我尝试使用手工制作的GetYouTubeVideoCommentFeedURL参数调整版本时遇到的错误:

gdata.service.RequestError: {'status': 400, 'body': 'You cannot request beyond item 1000.', 'reason': 'Bad Request'}

注意,同样的原则应该适用于检索API的其他提要中的条目。

如果要手工创建GetYouTubeVideoCommentFeedURL参数,其格式为:

'https://gdata.youtube.com/feeds/api/videos/{video_id}/comments?start-index={sta‌​rt_index}&max-results={max_results}'

以下限制适用:start-index <= 1000max-results <= 50

相关问题 更多 >

    热门问题