使用Webdriver下载PDF

时间:2013-10-07 22:47:53

标签: macos firefox python-2.7 selenium-webdriver

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

我实际上需要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,而不是下载它。

我通过请求仔细检查了内容类型,并将其确认为“application / pdf”:

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

知道我做错了什么?

2 个答案:

答案 0 :(得分:1)

有时会遇到类似的情况。解决方案非常简单。默认情况下,firefox中的设置会打开pdf文件,而不是允许您下载它。要克服此类型配置:在浏览器中输入并键入pdfjs.disabled,双击该选项。该值应从false更改为true。重新启动浏览器并尝试打开任何pdf文件。它将下载文件,而不是在浏览器中打开它。快乐的编码。

答案 1 :(得分:0)

我遇到了同样的问题。我的代码是用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 );