簡體   English   中英

使用帶有Selenium和Python的無頭瀏覽器保存頁面

[英]Saving a page using a headless browser with Selenium and Python

我正在尋找一種使用Selenium和Python保存完整網頁的方法,但是要使用無頭瀏覽器。 我希望保存的頁面與打開頁面時的外觀完全相同(就像在瀏覽器中使用“另存為...”功能一樣。)

我嘗試了Andersson( https://stackoverflow.com/a/42900364 )的這段代碼,它工作正常,但我想改用無頭瀏覽器。 這可能嗎?

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無頭瀏覽器。

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的路徑。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM