python - 抓取动态 HTML(YouTube 评论)

标签 python web-scraping beautifulsoup python-requests dynamic-html

借助 Beautiful Soup 和 Request Library,我能够抓取 HTML 内容,但无法抓取通过 JavaScript 或 AJAX 调用加载的内容。

我如何通过我的 Python 脚本模仿它?因为滚动页面时会加载 YouTube 评论。我找到了两种方法;一个使用 Selenium,另一个使用 lxml 请求,我有点看不懂。

示例(this is the video):

import requests
from bs4 import BeautifulSoup as soup

url = 'https://www.youtube.com/watch?v=iFPMz36std4'
response = requests.get(url)
page_html = response.content
#print page_html

page_soup=soup(page_html,"html.parser")
print page_soup

最佳答案

你需要使用 Selenium :

这里有一个技巧,Youtube 仅在您向下滚动视频时才加载评论,如果您滚动到底部或其他地方,则不会加载评论,因此请先滚动到该向下部分,然后滚动到底部或等待加载评论随时随地:

from selenium import webdriver

import time

driver=webdriver.Chrome()

driver.get('https://www.youtube.com/watch?v=iFPMz36std4')

driver.execute_script('window.scrollTo(1, 500);')

#now wait let load the comments
time.sleep(5)

driver.execute_script('window.scrollTo(1, 3000);')



comment_div=driver.find_element_by_xpath('//*[@id="contents"]')
comments=comment_div.find_elements_by_xpath('//*[@id="content-text"]')
for comment in comments:
    print(comment.text)

部分输出:

#can't post full output its too long
I love Kygo's Stranger Things and Netflix's Stranger Things <3
Stranger Things, Kygo and OneRepublic, could it be better?
Amazing Vibe!!!!!!!!!🔥🔥🔥🔥

关于python - 抓取动态 HTML(YouTube 评论),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47039874/

相关文章:

python - Unicode 转义文件处理错误

python - 使用切片列表从 DataFrame 获取行

python - Numpy 标准差不适合我

python - 无法从网站下载 pdf 文件

python - 创建非 nan 矩阵交叉点的掩码

python - 在 Selenium 中使用 find_element_by_class_name 遍历多个类

python - PyQt:QImage() 返回一个 'Null' -Image

c# - .ToDictionary C# 中的 foreach 和索引

python - 如何从 python beautiful soup 的表中获取 tbody?

python - 如何通过自动下载链接使用 Python 访问 PDF 文件?