首页 > 解决方案 > 如何抓取 youtube 评论及其发布日期

问题描述

我正在用硒抓取youtube 视频。我想要得到的结果是评论列表。每条评论都有它的发布日期。

现在我可以单独在列表中获取评论和单独发布评论的时间。我尝试运行这两个列表并使用日期列表的第 n 个元素编写评论列表的 ech 'n' 元素,但这并没有给我想要的结果。这是我的代码:

#get comments
comment_div=driver.find_element_by_xpath('//*[@id="contents"]')
comments=comment_div.find_elements_by_xpath('//*[@id="content-text"]')**

#get date
times=comment_div.find_elements_by_xpath('//*[contains(@class,"yt-simple- 
endpoint style-scope yt-formatted-string")]')

#print result
for i in range(len(times)):
    print(comments[i].text + ' , ' + times[i].text)

标签: pythonweb-scraping

解决方案


假设每条评论都有一个发布时间,您可以使用zip来合并两个列表。

# Assuming we two lists with the same length
comments = [ "comment1", "comment2", "comment3", "comment4" ] 
post_times = [ "t1","t2","t3","t4" ] 
comments_ex = zip(comments,post_times) 
for comment in comments_ex:
  print(comment)

输出

('comment1', 't1')
('comment2', 't2')
('comment3', 't3')
('comment4', 't4')

推荐阅读