使用 Selenium 和 IE 浏览器保存 PDF

Save PDF by using Selenium and IE Browser

使用 CHrome 浏览器保存 PDF 不会导致任何问题(我正在使用这些选项):

    options.add_experimental_option('prefs',{
    'credentials_enable_service': False,
    'plugins':{
        'always_open_pdf_externally': True
    },
    'profile': {
        'password_manager_enabled': False,
    },
    'download': {
        'prompt_for_download': False,
        'directory_upgrade': True,
        'default_directory': ''
    }
})

但是 ....如何使用 webdriver.Ie() Internet Explorer 驱动程序和 Python + Selenium 来保存 PDF?

P.S。 AFAIK Internet Explorer 无法使用无头模式执行,但如果有人不会这样做,那将是惊人的!!!

您不能使用 Selenium 来处理 IE 中的下载提示,因为那是 OS 级别的提示。 Selenium WebDriver 无法自动执行 OS 级提示 window。您需要使用一些第三方工具来帮助您使用 Selenium 在 IE 中下载文件。

这里我用Wget to bypass the download prompt and download file in IE. You can refer to this article讲述Wget的使用方法

关于在 Selenium 的 IE 中使用无头模式,您还可以使用名为 headless_ie_selenium 的第 3 方工具。您可以下载此工具并使用 headless_ie_selenium.exe 而不是 IEDriverServer.exe 来自动化 IE。

下载pdf文件的示例代码如下,请注意将代码中的路径改为自己的:

from selenium import webdriver
import time
import os

url = "https://file-examples.com/index.php/sample-documents-download/sample-pdf-download/"
driver = webdriver.Ie('D:\headless-selenium-for-win-v1-4\headless_ie_selenium.exe')
driver.get(url)

time.sleep(3)

link = driver.find_elements_by_class_name("download-button")[0]
hrefurl = link.get_attribute("href")

os.system('cmd /c C:\Wget\wget.exe -P D:\Download --no-check-certificate ' + hrefurl)

print("*******************")