【问题标题】:How to download a HTML webpage using Selenium with python?如何使用 Selenium 和 python 下载 HTML 网页?
【发布时间】:2017-08-11 12:44:59
【问题描述】:

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

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。 有什么方法可以调出“另存为”对话框吗?

谢谢 卡兰

【问题讨论】:

    标签: python python-3.x selenium selenium-chromedriver


    【解决方案1】:

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

    from selenium import webdriver
    
    driver = webdriver.Chrome()
    driver.get("http://www.yahoo.com")
    with open("/path/to/page_source.html", "w") as f:
        f.write(driver.page_source)
    

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

    更新

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

    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}")
    

    【讨论】:

    • 好友,感谢您的及时回复。但我收到以下错误: Traceback(最近一次调用最后一次):文件“C:\Users\karanjuneja\Desktop\Eclipse Workspace\Library\test1.py”,第 35 行,在 f.write(driver. page_source) 文件“C:\Users\karanjuneja\AppData\Local\Programs\Python\Python35-32\lib\encodings\cp1252.py”,第 19 行,编码返回 codecs.charmap_encode(input,self.errors,encoding_table) [0] UnicodeEncodeError: 'charmap' 编解码器无法编码位置 106288-106293 中的字符:字符映射到
    • 我想将文件保存为 .mhtml 格式。我使用了以下代码: from selenium import webdriver driver = webdriver.Chrome() driver.get("yahoo.com") with open("/path/to/page_source.html", "w", encoding="utf-8 ") as f: f.write(driver.page_source) 它保存了页面,但页面只有源代码。无法查看页面上的原始内容。有什么建议吗?
    • 您的意思是您希望浏览器打开本地(下载的)页面副本,就像您直接从服务器获取它一样?
    • 是的哥们,就像我们打开它时出现的网页一样。
    • :非常感谢您的回答。您能否为 ChromeDriver 提供与我使用 Chrome 浏览器相同的解决方案。将感激不尽。 :)
    猜你喜欢
    • 2017-05-12
    • 2017-10-19
    • 2018-01-29
    • 2020-05-12
    • 1970-01-01
    • 1970-01-01
    • 2019-11-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多