python - Selenium 下载整个 html

标签 python selenium dom web-scraping pageloadstrategy

我一直在尝试使用 Selenium 来抓取整个网页。我预计其中至少有一小部分是 spa,例如 Angular、React、Vue,所以这就是我使用 Selenium 的原因。

我需要下载整个页面(如果某些内容因为没有向下滚动而没有从延迟加载中加载,那很好)。我试过设置 time.sleep() 延迟,但没有奏效。获得页面后,我希望对其进行哈希处理并将其存储在数据库中,以便稍后进行比较并检查内容是否已更改。目前哈希值每次都不同,这是因为 selenium 没有下载整个页面,每次都缺少不同的部分量。我已经在多个网页上确认了这一点,而不仅仅是一个网页。

我可能还有 1000 多个网页需要手动浏览,只是获取所有链接,所以我没有时间在它们上面找到一个元素来确保它已加载。

这个过程需要多长时间并不重要。如果需要 1 个多小时,那就这样吧,速度并不重要,重要的只是准确性。

如果您有其他想法,也请分享。

我的司机声明

 from selenium import webdriver
 from selenium.common.exceptions import WebDriverException

 driverPath = '/usr/lib/chromium-browser/chromedriver'

 def create_web_driver():
     options = webdriver.ChromeOptions()
     options.add_argument('headless')

     # set the window size
     options.add_argument('window-size=1200x600')

     # try to initalize the driver
     try:
         driver = webdriver.Chrome(executable_path=driverPath, chrome_options=options)
     except WebDriverException:
         print("failed to start driver at path: " + driverPath)

     return driver

我的 url 调用 我的超时 = 20

 driver.get(url)
 time.sleep(timeout)
 content = driver.page_source

 content = content.encode('utf-8')
 hashed_content = hashlib.sha512(content).hexdigest()

^ 每次都在这里得到不同的哈希值,因为相同的 url 不会产生相同的网页

最佳答案

由于被测应用程序 (AUT) 基于 AngularReactVue 在这种情况下Selenium 似乎是完美的选择。

现在,由于您对 某些内容由于不滚动而未从延迟加载中加载 的事实感到满意,因此 用例可行的。但是在所有可能的方式中 ...没有时间在它们上面找到一个元素以确保它被加载... 不能真正补偿诱导 time.sleep() 因为 time.sleep() 有一些缺点。您可以在 How to sleep webdriver in python for milliseconds 中找到详细的讨论。 .值得一提的是 HTML DOM 的状态所有 1000 个奇数网页都会不同。

解决方案

几个可行的解决方案:

如果您实现 pageLoadStrategypage_source 方法将在相同的触发点触发,您可能会看到相同的 hashed_content

关于python - Selenium 下载整个 html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52696433/

相关文章:

PHP DOM - 计算子节点?

python - 如何从打印消息并关闭程序的函数创建单元测试?

Python super(Class, self).method vs super(Parent, self).method

java.lang.NoClassDefFoundError : org/apache/commons/exec/Executor 错误

angularjs - 包含任何文本的元素的 Protractor 预期条件

c# - 在 Selenium Webdriver 中读取分页数据网格

java - 如何获取 HTML <body> 的内容

javascript - 使用 JavaScript 返回 click li 项的值并用结果填充文本区域

python - pytz - 将 UTC 和时区转换为本地时间

python - OpenCV 中保存的 webp 图像比 jpg 大 3 倍