【问题标题】:Saving a page using a headless browser with Selenium and Python使用带有 Selenium 和 Python 的无头浏览器保存页面
【发布时间】:2019-12-03 05:05:34
【问题描述】:

我正在寻找一种使用 Selenium 和 Python 保存完整网页的方法,但使用的是无头浏览器。而且我希望保存的页面与我们打开它时网页的显示方式完全相同(就像使用浏览器中的“另存为...”功能一样。)

我尝试了 Andersson (https://stackoverflow.com/a/42900364) 的这段代码 sn-p,它运行良好,但我想改用无头浏览器。这可能吗?

from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
import ahk

firefox = FirefoxBinary("C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe")
from selenium import webdriver

driver = web.Firefox(firefox_binary=firefox)
driver.get("http://www.yahoo.com")
ahk.start()
ahk.ready()
ahk.execute("Send,^s")
ahk.execute("WinWaitActive, Save As,,2")
ahk.execute("WinActivate, Save As")
ahk.execute("Send, C:\\path\\to\\file.htm")
ahk.execute("Send, {Enter}")

【问题讨论】:

    标签: python selenium selenium-webdriver web-scraping headless-browser


    【解决方案1】:

    你能试试这个代码吗?
    我在这个例子中使用的是 chrome 无头浏览器。

    from selenium import webdriver
    import io
    
    options = webdriver.ChromeOptions()
    options.add_argument("--headless")
    driver = webdriver.Chrome("driver/chromedriver.exe", options=options) #Change chromedriver path accordingly
    driver.get("https://stackoverflow.com")
    driver.implicitly_wait(10)
    html = driver.page_source
    with io.open(driver.title + ".html", "w", encoding="utf-8") as f:
        f.write(html)
        f.close()
    driver.quit()
    

    成功执行后,html文件将保存在运行此代码的同一目录中。这应该与浏览器的“另存为”功能完全一样。
    注意:相应地更改 chromedriver 的路径。

    【讨论】:

      猜你喜欢
      • 2018-11-15
      • 1970-01-01
      • 1970-01-01
      • 2013-02-17
      • 1970-01-01
      • 2020-10-01
      • 2023-04-01
      • 2021-10-06
      • 2014-08-29
      相关资源
      最近更新 更多