【问题标题】:Downloading PDF's with Webdriver使用 Webdriver 下载 PDF
【发布时间】:2013-10-14 16:37:51
【问题描述】:

我正在尝试在 OS X 10.8 上使用带有 python 绑定的 selenium webdriver 下载 pdf。

我实际上需要 pdf 文件,而不仅仅是检查下载链接是否有效。据我了解,我需要设置 firefox 配置文件来下载 pdf 内容类型,而不是默认的“预览”。

我打开firefox实例的代码是:

def Engage():
    print "Start Up FIREFOX"
    ## Create a new instance of the Firefox driver
    profile = webdriver.firefox.firefox_profile.FirefoxProfile()
    profile.set_preference('browser.download.folderList', 2)
    profile.set_preference('browser.download.dir', os.path.expanduser("~/Documents/PYTHON/Download_Files/tmp/"))
    profile.set_preference('browser.helperApps.neverAsk.saveToDisk', ('application/pdf'))
    driver = webdriver.Firefox(firefox_profile=profile)
    return driver

我也尝试过最初将配置文件设置为:

profile = webdriver.FirefoxProfile()
## replacing :: profile = webdriver.firefox.firefox_profile.FirefoxProfile()
## the other attributes remained

结果相同

此配置文件在新窗口中以预览模式打开 pdf,而不是下载它。

我通过请求再次检查了内容类型,并能够确认它是“应用程序/pdf”:

import requests
print requests.head('mywebsite.com').headers['content-type']

知道我做错了什么吗?

【问题讨论】:

    标签: macos firefox python-2.7 selenium-webdriver


    【解决方案1】:

    我也遇到了同样的问题。我的代码是用 Java 编写的,但我确信您可以将属性转移到 python 中匹配。这是我的工作(请注意,您需要指定可以写入的目录的路径):

    FirefoxProfile profile = new FirefoxProfile();
    profile.setPreference( "browser.download.folderList", 2 );
    profile.setPreference( "browser.download.dir", <YOUR DOWNLOAD PATH> );
    profile.setPreference( "plugin.disable_full_page_plugin_for_types", "application/pdf" );
    profile.setPreference(
                    "browser.helperApps.neverAsk.saveToDisk",   
    "application/csv,text/csv,application/pdfss, application/excel" );
    profile.setPreference( "browser.download.manager.showWhenStarting", false );
    profile.setPreference( "pdfjs.disabled", true );
    

    【讨论】:

      【解决方案2】:

      曾经面临过类似的情况。解决方法很简单。默认情况下,Firefox 中的设置会打开 pdf 文件,而不是允许您下载它。要克服这种类型 config:about 在浏览器中并键入 pdfjs.disabled 双击该选项。该值应从 false 更改为 true。重新启动浏览器并尝试打开任何 pdf 文件。它将下载文件而不是在浏览器中打开它。编码愉快。

      【讨论】:

      • 我真的认为这会做到这一点,虽然它在我的默认浏览器自动下载上生成了 pdf,但它不会在 webdriver 创建的 firefox 实例中下载 pdf。我需要找到一种方法来对 webdriver 的配置文件进行配置更改。不过还是谢谢你的建议。
      • 为什么不在新的 Firefox 配置文件中更改此值并启动该配置文件。它对我有用。只是一个建议。
      • 如果我每次使用 webdriver 时 firefox 都会启动一个新的配置文件,我将如何更改它?我试图设置配置文件无济于事。有没有办法打开 firefox,使用 webdriver 更改 about:config 页面,然后在同一配置文件中重新启动 firefox?
      • @ExperimentsWithCode 您必须创建您的 firefox 配置文件并更改其中的设置并在启动 firefoxdriver 时调用该配置文件。要创建新的配置文件,请关闭 firefox。转到运行对话框并键入 firefox -ProfileManager。按照步骤为 Ex 创建配置文件。 Selenium 并启动 firefox。现在更改pdf设置。完成后,使用以下代码调用此配置文件。 ProfilesIni sel = 新的 ProfilesIni(); FirefoxProfile pro = sel.getProfile("Selenium"); WebDriver driver = new FirefoxDriver(pro);
      • 它在“ProfilesIni sel=new ProfilesIni();”中显示“sel”语法无效。
      猜你喜欢
      • 1970-01-01
      • 2018-03-08
      • 2017-03-09
      • 2017-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-21
      • 1970-01-01
      相关资源
      最近更新 更多