我正在寻找一种使用 Selenium 和 Python 保存完整网页的方法,但使用 headless 浏览器。我希望保存的页面与我们打开网页时的显示效果完全相同(就像在浏览器中使用“另存为...”功能一样。)
我尝试了 Andersson ( https://stackoverflow.com/a/42900364 ) 的代码片段,它工作正常,但我想使用 headless 浏览器。这可能吗?
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}")
最佳答案
你可以尝试一下这个代码吗。
我在本例中使用 chrome headless 浏览器。
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 的路径。
关于python - 使用带有 Selenium 和 Python 的 headless 浏览器保存页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57193162/