如何抓取YouTube评论及其发布日期

时间:2019-05-01 11:30:50

标签: python web-scraping

我正在用硒废弃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)

1 个答案:

答案 0 :(得分:1)

在每个评论都带有发布时间的假设下,您可以使用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')