【问题标题】:Saving pages with Selenium使用 Selenium 保存页面
【发布时间】:2018-09-03 01:13:35
【问题描述】:

我会再试一次。

我从另一个网站复制下面的代码,用户说它有效(显示截图)。Original code

我测试了代码:没有错误,但没有文件保存。

所有问题都使用此答案保存文件:A question!

为什么页面没有保存,如果保存了,文件在哪里?

谢谢

from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys

driver = webdriver.Chrome(executable_path=r"C:\Program Files (x86)\Selenium\chromedriver.exe")

driver.get("http://www.example.com")

saveas = ActionChains(driver).key_down(Keys.CONTROL).send_keys('S').key_up(Keys.CONTROL)

saveas.perform()

【问题讨论】:

    标签: python selenium google-chrome


    【解决方案1】:
    from selenium import webdriver
    
    driver = webdriver.Chrome(executable_path=r"C:\Program Files (x86)\Selenium\chromedriver.exe")
    
    driver.get("http://www.example.com")
    with open('page.html', 'w+') as f:
        f.write(driver.page_source)
    

    必须工作

    【讨论】:

      【解决方案2】:

      如果您在浏览器中进行组合键,您将看到这只会弹出“保存页面”对话框。您需要另外发送 ALT+S 来保存页面,在 Windows 中它将默认保存在您的下载文件夹中。

      saveas = ActionChains(driver).key_down(Keys.CONTROL).send_keys('S').key_up(Keys.CONTROL).send_keys('MyDocumentName').key_down(Keys.ALT).send_keys('S').key_up(Keys.ALT)
      

      编辑: ActionChains 是不可靠的。不与浏览器 GUI 交互会更容易。

      from selenium import webdriver
      
      driver = webdriver.Chrome(executable_path=r"C:\Program Files (x86)\Selenium\chromedriver.exe")
      
      driver.get("http://www.example.com")
      with open('page.html', 'w') as f:
          f.write(driver.page_source)
      

      【讨论】:

      • 它似乎与版本有关。确认无法在最新的 Chrome 和 Firefox 上运行。
      猜你喜欢
      • 1970-01-01
      • 2012-06-13
      • 2014-04-17
      • 2019-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-16
      • 2018-10-26
      相关资源
      最近更新 更多