How to Download File using Selenium and Verifying file exists

In our last post, we discussed how you can upload files using webdriver. In this post, we will learn how to download files from a web browser using Selenium. If you run your script in a different browser, the file download behavior differs.

During the automation in some web applications, we need to download the file, and that file may be in different formats like MS Excel file, MS Word File, Zip file, PDF file, CSV file, Text file, etc. The main problem in dealing with such cases is when you click the download link or button, a new window will open, which is a window-based application. As you know, by using Selenium webdriver, we can not handle Windows-based applications using Selenium.

The settings for different browsers vary for downloading files, such as downloading the file default or sometimes displaying a system pop-up. To deal with the different file formats downloaded in the Firefox browser, we can use the help of the Firefox profile. Before learning how to 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 have a list of MIME types, So they transfer the same file over the internet in the same way and type, no matter what operating system they are working in.

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

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

Some MIME-type list of most 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 about is that you are coming to this post for how to download files using Selenium webdriver; then, why are we discussing MIME types? We discussed these things because we will 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 run the above script, you can find that the required file is downloaded in the specified location.

Below, we have mentioned different preference settings which help 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 the 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 the 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 allows the 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 closes 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 will leave the window in the background when starting a download.

How do you 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 the address bar, type About config and press enter.
  • Search for Never Ask and hit Enter, and then you will get some options like the screen below.
    Enter the screenshot
  • For the “browser.helperApps.neverAsk.openFile;” row in the value column is blank, we need to set the desired property by specifying the file type so that the Firefox browser will not ask permission to download files.

Ensure you open the same profile, as Selenium always picks up the default one.

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: Internet Explorer does NOT support browser profile preferences. 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

Avatar for Softwaretestingo Editorial Board

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