无法使用Selenium Firefox自动保存文件

时间:2018-01-29 11:57:59

标签: selenium firefox

我使用Selenium点击Firefox中的链接,我希望它能自动下载该文件。 我查看了互联网公司的各种资源。 Selenium firefox profile for saving a file。 &安培; Set Firefox profile to download files automatically using Selenium and Java。但我无法让它发挥作用。它只是给我一个打开/保存对话框的提示。 我使用的是Firefox 57.0.2,firefox驱动程序3.8.1,Geckodriver 0.19.1。 我可以手动设置firefox选项来保存文件,但在代码中我创建了一个新的配置文件,所以这显然会被忽略。 我的代码是:

System.setProperty(webdriver.gecko.driver",System.getProperty("user.dir") + Constants.GECKODRIVER);

FirefoxOptions firefoxOptions = new FirefoxOptions();
FirefoxProfile profile = new FirefoxProfile();

profile.setPreference("browser.download.dir", dirPath);
profile.setPreference("browser.download.folderList",2);
profile.setPreference("browser.helperApps.neverAsk.openFile","application/pdf,text/plain,application/octet-stream,application/x-pdf,application/vnd.pdf,application/vnd.openxmlformats-officedocument.spreadsheethtml,text/csv,text/html,application/x-msexcel,application/excel,application/x-excel,application/vnd.ms-excel");
profile.setPreference("browser.helperApps.neverAsk.saveToDisk","application/pdf,text/plain,application/octet-stream,application/x-pdf,application/vnd.pdf,application/vnd.openxmlformats-officedocument.spreadsheethtml,text/csv,text/html,application/x-msexcel,application/excel,application/x-excel,application/vnd.ms-excel");
profile.setPreference("browser.helperApps.alwaysAsk.force, false);
profile.setPreference("browser.download.manager.useWindow, false);
profile.setPreference("browser.download.manager.focusWhenStarting, false);
profile.setPreference("browser.download.manager.alertOnEXEOpen, false);
profile.setPreference("browser.download.manager.showAlertOnComplete, false);
profile.setPreference("browser.download.manager.closeWhenDone, false);
profile.setPreference("browser.allowpopups, false);
profile.setPreference("pdfjs.disabled",true);
profile.setAcceptUntrustedCertificates(true);
profile.setAssumeUntrustedCertificatesIssuer(true);
firefoxOptions.setProfile(profile);
currentdriver = new FirefoxDriver();

我甚至尝试过

profile.setPreference("plugin.disable_full_page_plugin_for_types","application/pdf,application/x-pdf");
profile.setPreference("plugin.scan.Acrobat,"99.0");

我已经尝试查看我需要的2个文件的MIME类型(.pdf和.xlsx),我认为它们是text / html; charset = iso-8859-1。

建议吗?

1 个答案:

答案 0 :(得分:0)

我也没有成功使用来自硒的webdriver.FirefoxProfile中的set_preference。起作用的是修改了firefox配置文件目录中的handlers.json文件。

必须在json文件的mimeTypes下插入以下内容:

"application/text":{"action":0,"extensions":["csv"]},