如何在Java中使用Selenium通过Firefox下载XLSX文件



我正在尝试使用以下代码下载 xlsx 文件:

FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("browser.download.dir", "directory where to save data");
profile.setPreference("browser.download.folderList", 2);
profile.setPreference("browser.helperApps.alwaysAsk.force", false);
profile.setPreference("browser.download.manager.showWhenStarting", false);
profile.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/x-excel, application/x-msexcel, application/excel, application/vnd.ms-excel");
ob = new FirefoxDriver(profile);

但是测试在显示下载对话框后停止,并且不会下载任何文件。

但是,如果我通过更改上述代码中提到的 mime 类型来尝试相同的 csv 文件代码,那么它可以正常工作。

请帮助我。谢谢。

我添加了以下内容,而不是上面的代码:

firefoxProfile.setPreference("browser.download.dir",dest_path);
firefoxProfile.setPreference("browser.download.manager.showWhenStarting",false);
firefoxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk","application/xls;text/csv");

现在它工作正常。xlsx 的 MIME 类型无法正常工作,所以我尝试将 MIME 类型放入 xls 文件,现在它工作正常。XLSX 文件正在自动下载。

只需使用此代码:

profile.set_preference("browser.helperApps.neverAsk.saveToDisk", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")

看起来您正在下载的文件的 MIME 类型不同(可能类似于 application/force-download ),正如您提到的,xlsx 的正确 MIME 类型 - application/vnd.openxmlformats-officedocument.spreadsheetml.sheet .

安装"HTTPFox"火狐插件来记录流量并检查其中捕获的实际MIME类型。使用该 MIME 类型更新后,您的代码应该可以正常工作。

最新更新