简体   繁体   English

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

[英]How to download XLSX file through firefox using Selenium in Java?

I am trying to download an xlsx file using the following code:我正在尝试使用以下代码下载 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);

But the test stops after displaying the download dialog box, and it is not downloading any file.但是在显示下载对话框后测试停止,并且没有下载任何文件。

But if i try the same code for csv file by changing the mime type mentioned in the above code, then it works fine.但是如果我通过更改上面代码中提到的 mime 类型来尝试对 csv 文件使用相同的代码,那么它工作正常。

Please help me.请帮我。 Thank you.谢谢你。

Instead of the above code I added following:我添加了以下代码,而不是上面的代码:

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

And now it is working fine.现在它工作正常。 The MIME type for xlsx was not working properly so instead i tried to put the MIME type for xls file and now it is working fine. xlsx 的 MIME 类型无法正常工作,因此我尝试为 xls 文件放置 MIME 类型,现在它工作正常。 The XLSX file is getting downloaded automatically. XLSX 文件正在自动下载。

只需使用此代码:

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

Looks like MIME type for file that you are downloading is different (may be something like application/force-download ), as you have mentioned correct MIME type for xlsx - application/vnd.openxmlformats-officedocument.spreadsheetml.sheet .看起来您正在下载的文件的 MIME 类型不同(可能类似于application/force-download ),正如您提到的 xlsx 的正确 MIME 类型 - application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

Install "HTTPFox" Firefox plugin to record the traffic and check the actual MIME type captured in it.安装“HTTPFox”Firefox 插件来记录流量并检查其中捕获的实际 MIME 类型。 Once update with that MIME type, your code should work.使用该 MIME 类型更新后,您的代码应该可以工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM