How to Download File using Selenium and Verifying file exists

In our last post, we have discussed in details about how you can upload files using webdriver. In this post, we are going to learn about how we can download files from a web browser using Selenium. If you run your script in a different browser, then the file download behaviour is different.

During the automation in some web application, we need to download the file and that file may be in different format like MS Excel file, MS Word File, Zip file, PDF file, CSV file, Text file, etc. The main problem to deal such cases is when you click the download link or button that time a new window will be opening which is a window based application and as you know that by using selenium webdriver we can not handle windows based application using Selenium.

For different browser, the settings for download files vary which like downloading the file default or some time it displays a system pop-up. To deal with the different file format download in Firefox browser we can take help of the firefox profile. Before we start learning how we can handle the download file scenarios, let us understand the different MIME types.

What is MIME Type?

The Full form of MIME is Multipurpose Internet Mail Extensions. This is used to classify the file types on the internet. On the internet the different servers and browsers which all the list of MIME types, So they transfer the same file over internet in the same way and type, no matter what operating system they are working in.

A MIME has two parts, where one part represents the type and the other part represents subtype. Here each part is separated by a slash (/).

Let us take an example for a Microsoft word file where the type is application and the subtype is msword. By together both of this the complete MIME type is application/msword. You can get all the complete list of MIME type here.[https://www.sitepoint.com/mime-types-complete-list/]

Some MIME type list of mostly used files:

  • Text File (.txt) – text/plain
  • PDF File (.pdf) – application/pdf
  • CSV File (.csv) – text/CSV
  • MS Excel File (.xlsx) – application/vnd.openxmlformats- officedocument.spreadsheetml.sheet
  • MS Word File (.docx) – application/vnd.openxmlformats-officedocument. wordprocessingml. document

One thing you may be confused that you are coming to this post for how to download files using selenium webdriver then why we are discussing MIME types, let me told you we had discussed these things because we are going to use the MIME type in our selenium automation script firefox profile.

How to Download files using Selenium?

We Can perform the file download by following the below steps, and those steps are:

  • Create a Firefox profile
  • Set the preference as per the requirement.
  • Open the Firefox browser with the Firefox profile.

Let us implement the same things through the automation script:

package seleniumPrograms;
import org.openqa.selenium.By;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;

public class DownloadFiles_FireFoxProfile
{
   public static void main(String[] args) throws InterruptedException 
   {
      //Create FireFox Profile object
      FirefoxProfile profile = new FirefoxProfile();

      //Set Location to store files after downloading.
      profile.setPreference("browser.download.dir", "D:\\WebDriverDownloads");
      profile.setPreference("browser.download.folderList", 2);

      //Set Preference to not show file download confirmation dialogue using MIME types Of different file extension types.
      profile.setPreference("browser.helperApps.neverAsk.saveToDisk",
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;");

      profile.setPreference( "browser.download.manager.showWhenStarting", false );
      profile.setPreference( "pdfjs.disabled", true );

      //Pass FProfile parameter In webdriver to use preferences to download file.
      FirefoxDriver driver = new FirefoxDriver(profile);

      // Open APP to download application
      driver.get("http://toolsqa.com/automation-practice-form/");

      // Click to download
      driver.findElement(By.linkText("Test File to Download")).click();

      //Halting the execution for 5 secs to donwload the file completely
      Thread.sleep(5000);

      driver.close();
   }
}

If you are run the above script then you can find out the required file is downloaded in the specified location.

Below we have mentioned different preference settings, which helps you to handle various situations:

1. setPreference(“browser.download.folderList”, 2);

Default Value: 0

This can be set to either 0, 1, or 2. When set to 0, Firefox will save all files on the user’s desktop. 1 saves the files in the Downloads folder and 2 saves file at the location specified for the most recent download.

2. setPreference(“browser.download.manager. showWhenStarting”, bool);

Default Value: true

It allows the user to specify whether or not the Download Manager window is displayed when a file download is initiated.

3. setPreference(“browser.helperApps.alwaysAsk .force”, bool);

Default Value: true

Always ask what to do with an unknown MIME type, and disable the option to remember what to open it with False (default): Opposite of above

4. setPreference(“browser.helperApps.neverAsk. saveToDisk”,value);

Default Value: empty string

A comma-separated list of MIME types to save to disk without asking what to use to open the file.

5. setPreference(“browser.helperApps.neverAsk. openFile”,value);

Default Value: empty string

A comma-separated list of MIME types to open directly without asking for confirmation.

6. setPreference(“browser.download.dir”,path);

Default Value: empty string

The directory to save the file.

7. setPreference(“browser.download.manager. alertOnEXEOpen”,bool);

Default Value: true

Warn the user was attempting to open an executable from the Download Manager. False displays no warning and allow executable to be run.
Note: In Firefox, this can be changed by checking the “Don’t ask me this again” box when you encounter the alert.

8. setPreference(“browser.download.manager. closeWhenDone”,bool);

Default Value: false

True close the Download Manager, when all downloads are complete and False, is the opposite.

9. setPreference(“browser.download.manager. focusWhenStarting”,bool);

Default Value: false

True will set the Download Manager window as active when starting a download and False leaves the window in the background when starting a download.

How to set FireFox Profile settings manually to Download files using Selenium?

We can set all the settings manually in the Firefox browser by following the below steps:

  • Open Firefox browser and in address bar type about config and press enter
  • Search for never ask and hit enter, and then you will get some options likes below screen
    Enter the screenshot
  • For “browser.helperApps.neverAsk.openFile;” row in the value column blank, so we need to set the desired property by specifying the file type. So that the firefox browser will not ask for permission to download files.

Make sure you open the same profile, as Selenium always picks up the default profile.

Download files in Firefox browser using Selenium WebDriver
This script will download Adobe Reader from Filehippo.com

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;

public class DownloadFile 
{
   //Set downloadPath
   public static String downloadPath = “C:\\Users\\deepansagarwal\\Downloads”;
   public static void main(String args[]) throws Exception
   {
      //Set System property for Firefox Gecko driver
      System.setProperty(“webdriver.gecko.driver”,”C:\\Downloads\\geckodriver.exe”);

      //Start a Firefox session using FirefoxDriverProfile() function which returns a Firefox Profile
      WebDriver driver = new FirefoxDriver(FirefoxDriverProfile());

      //Wait & maximize window
      driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

      driver.manage().window().maximize();
      //Open URL

      driver.get(“http://filehippo.com/download_abdio_pdf_reader/”);
         //Click on Download

         driver.findElement(By.xpath(“.//*[@id=’program-header’]/div[4]/a[1]”)).click();
   }
   public static FirefoxProfile FirefoxDriverProfile() throws Exception 
   {
      FirefoxProfile profile = new FirefoxProfile();
      profile.setPreference(“browser.download.folderList”, 2);
      profile.setPreference(“browser.download.manager.showWhenStarting”, false);
      //Set downloadPath
      profile.setPreference(“browser.download.dir”, downloadPath);

      //Set File Open & Save preferences profile.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”);

      profile.setPreference(“browser.helperApps.neverAsk.saveToDisk”,
            “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”);

      profile.setPreference(“browser.helperApps.alwaysAsk.force”, false);
      profile.setPreference(“browser.download.manager.alertOnEXEOpen”, false);
      profile.setPreference(“browser.download.manager.focusWhenStarting”, false);
      profile.setPreference(“browser.download.manager.useWindow”, false);
      profile.setPreference(“browser.download.manager.showAlertOnComplete”, false);
      profile.setPreference(“browser.download.manager.closeWhenDone”, false);
      return profile;
   }
}

Note*: Browser profile preferences is NOT supported by Internet Explorer. As such, there is no way to automatically download files to a specified location with Internet Explorer / Edge Browser.

Download files in Chrome browser using selenium WebDriver

import java.util.HashMap;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;

public class DownloadChromeFile 
{
   public static void main(String[] args) 
   {
      System.setProperty(“webdriver.chrome.driver”,”./chromedriver.exe”);
      String downloadFilepath = “c:\\download”;

      HashMap<String, Object> chromePrefs = new HashMap<String, Object>();
      chromePrefs.put(“profile.default_content_settings.popups”, 0);
      chromePrefs.put(“download.default_directory”, downloadFilepath);
      ChromeOptions options = new ChromeOptions();

      HashMap<String, Object> chromeOptionsMap = new HashMap<String, Object>();
      options.setExperimentalOption(“prefs”, chromePrefs);
      options.addArguments(“–test-type”);
      options.addArguments(“–disable-extensions”); //to disable browser extension popup

      DesiredCapabilities cap = DesiredCapabilities.chrome();
      cap.setCapability(ChromeOptions.CAPABILITY, chromeOptionsMap);
      cap.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
      cap.setCapability(ChromeOptions.CAPABILITY, options);

      driver = new ChromeDriver(cap);
      driver.get(“http://www.seleniumhq.org/download/”);
         driver.findElement(By.linkText(“32 bit Windows IE”)).click();
   }
}

Note*:-Find the downloaded file under the specified folder – c:\download

I love open-source technologies and am very passionate about software development. I like to share my knowledge with others, especially on technology that's why I have given all the examples as simple as possible to understand for beginners. All the code posted on my blog is developed, compiled, and tested in my development environment. If you find any mistakes or bugs, Please drop an email to softwaretestingo.com@gmail.com, or You can join me on Linkedin.

Leave a Comment