gpt4 book ai didi

python - 如何使用带有 python 的 Selenium 下载 HTML 网页?

转载 作者:行者123 更新时间:2023-11-28 21:42:59 25 4
gpt4 key购买 nike

我想下载一个使用 selenium 和 python 的网页。使用以下代码:

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

chromeOptions = webdriver.ChromeOptions()
chromeOptions.add_argument('--save-page-as-mhtml')
d = DesiredCapabilities.CHROME
driver = webdriver.Chrome()

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

saveas = ActionChains(driver).key_down(Keys.CONTROL)\
.key_down('s').key_up(Keys.CONTROL).key_up('s')
saveas.perform()
print("done")

但是上面的代码不工作。我正在使用 Windows 7。有什么方法可以调出“另存为”对话框吗?

谢谢卡兰

最佳答案

您可以使用下面的代码下载页面HTML:

from selenium import webdriver

driver = webdriver.Chrome()
driver.get("http://www.yahoo.com")
with open("/path/to/page_source.html", "w", encoding='utf-8') as f:
f.write(driver.page_source)

只需将 "/path/to/page_source.html" 替换为所需的文件路径和文件名

更新

如果需要获取完整的页面源码(包括CSS, JS, ...),可以使用如下解决方案:

pip install pyahk # from command line

Python代码:

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 - 如何使用带有 python 的 Selenium 下载 HTML 网页?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42900214/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com