vsreekanth vsreekanth - 7 months ago 233
Java Question

How to handle download pop-up in firefox, while downloading excel using Selenium Webdriver

I am trying to download an Excel file from Firefox and Webdriver, but i can't handle the download pop-up.

When click on button i need the file to download automatically, without showing pop-up.

Here is my code:

FirefoxProfile firefoxProfile = new FirefoxProfile();
firefoxProfile.setPreference("browser.download.folderList", 2);
firefoxProfile.setPreference("browser.download.manager.showWhenStarting", false);
firefoxProfile.setPreference("browser.download.dir", Constant.Downloaded_Path);
firefoxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk", "text/csv/xls/xlsx");
firefoxProfile.setPreference("browser.helperApps.neverAsk.openFile",
"text/csv,application/x-msexcel,application/excel,application/x-excel,application/vnd.ms-excel,image/png,image/jpeg,text/html,text/plain,application/msword,application/xml");
firefoxProfile.setPreference("browser.helperApps.alwaysAsk.force", false);
firefoxProfile.setPreference("browser.download.manager.alertOnEXEOpen", false);
firefoxProfile.setPreference("browser.download.manager.focusWhenStarting", false);
firefoxProfile.setPreference("browser.download.manager.useWindow", false);
firefoxProfile.setPreference("browser.download.manager.showAlertOnComplete", false);
firefoxProfile.setPreference("browser.download.manager.closeWhenDone", false);
return firefoxProfile;


But, the above code is not working. Can any one help?

Answer

First you need to get the mime type corresponding to the file:

  • Open Developer Tools and then the Network tab
  • Go back to the page and click on the file to download
  • Go back to the network panel and select the first request
  • Copy the mime type on the right of Content-Type from the response header:

enter image description here

  • Set the preference "browser.helperApps.neverAsk.saveToDisk" with your mime type
  • Make sure the download folder "browser.download.dir" exists

Here is a working example with Firefox:

FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("browser.download.folderList", 2);
profile.setPreference("browser.download.dir", "C:\\Windows\\temp");
profile.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/vnd.ms-excel");
profile.setPreference("pdfjs.disabled", true);  // disable the built-in PDF viewer

WebDriver driver = new FirefoxDriver(profile);
driver.get("http://www.exinfm.com/free_spreadsheets.html");
driver.findElement(By.linkText("Capital Budgeting Analysis")).click();