Advance Selenium

How to Download files in Selenium Webdriver

Hello Welcome to Selenium tutorial, today we will see How to Download files using Selenium Webdriver.

In previous post, we have seen how to upload files using robot class and upload files using AutoIT. Today we will see some different scenario we will see downloading files in Selenium.

Sometime in your application, you have to control some scenario in which you need to download some files by clicking on some link or some button.

Once you start download files/application, you will get one confirmation window, which will ask to save, file or cancel here Webdriver stuck because this is Window’s Pop up. Selenium can handle only Web browser automation not windows based application. Refer below screenshot for more information.

Here download files window is displayed if you try to inspect using firebug you will not get any locators for them.
How to Download files using Selenium

So using some browser settings (firefoxprofile) we can skip that confirmation window and we can continue with our script.

Here is some setting that we need to modify let’s see how to check these setting

How to Download files in Selenium Webdriver

1- Open Firefox browser and in url box type about:config and press enter

2- In Search bar type neverask and enter, here you will find some settings(refer below screenshot)
How to Download files using Selenium

Now you can see here value is blank so we need to mention which type of file it will not ask if download starts in case.

Note- In this post I am giving values for .exe file(application), in your case if you want to download pdf, excel file etc. you need to mention values (MIME type).

Here you can find their MIME type that will be the values for these settings.

http://www.sitepoint.com/web-foundations/mime-types-complete-list/

How to Download files in Selenium Webdriver

Step 1- Create a firefox Profile.

Step 2- set Preferences as per requirement.

Step 3- Open Firefox with firefox profile.

Let us implement the same through Script.

Note- This script will download Adobe Reader from Filehippo.com

package blog;

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 DownloadFiles {

public static void main(String[] args) {
  
// Create a profile
FirefoxProfile profile=new FirefoxProfile();

// Set preferences for file type 
profile.setPreference("browser.helperApps.neverAsk.openFile", "application/octet-stream");
  
// Open browser with profile                   
WebDriver driver=new FirefoxDriver(profile);
  
// Set implicit wait
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
  
// Maximize window
driver.manage().window().maximize();
  
// Open APP to download application
driver.get("http://www.filehippo.com/download_adobe_reader");
  
// Click on download 
driver.findElement(By.xpath(".//*[@id='program-header']/div[4]/a[1]")).click();
    
 }

}

 

If you run above code files will be download automatically and download window will not appear 🙂

Please comment below if you have any issue in Selenium. Thanks for visiting my blog keep in touch.

Bye.

 

author-avatar

About Mukesh Otwani

I am Mukesh Otwani working professional in a beautiful city Bangalore India. I completed by BE from RGPV university Bhopal. I have passion towards automation testing since couple of years I started with Selenium then I got chance to work with other tools like Maven, Ant, Git, GitHub, Jenkins, Sikuli, Selenium Builder etc.

59 thoughts on “How to Download files in Selenium Webdriver

  1. divya says:

    Hi Mukesh,

    When i run my code it downloads .xls file but dont for xlsx .also it doesn’t give any error like element not found or anything . M working on chrome browser.is there a need to define mime type in chrome?kindly help.

    1. Hey Divya, for Chrome you don’t need to set any MIME type. You can just change the download directory and you can verify the same.

  2. Anurag says:

    How to do this in with ChromeDriver

    1. Hi Anurag,

      Try with below code
      Map prefsMap = new HashMap();
      prefsMap.put(“profile.default_content_settings.popups”, 0);
      prefsMap.put(“download.default_directory”, “Path of the download folder”);
      ChromeOptions option = new ChromeOptions();
      option.setExperimentalOption(“prefs”, prefsMap);
      WebDriver driver = new ChromeDriver(option);

  3. Sanjay says:

    This is very helpful and very easy to follow. Thanks for the post.

    1. Hi Sanjay,

      You’re welcome…:)

  4. Rizwana says:

    Hi Mukesh,

    I am getting an error at the line driver=new FirefoxDriver(profile); Error is ‘The Constructor FirefoxDriver(FirefoxProfile) is undefined’. Please help me to resolve this issue. I am using Firefox 62 and selenium 3.7.1

    1. Hi Rizwana,

      FirefoxProfile has to used with FirefoxOptions from version 3.6.0 onwards. Here is the link for more understandibility https://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/firefox/FirefoxOptions.html

      1. shushma says:

        Hi Mukesh,

        i was getting same error and also i have gone through your link error resolved. But its not clicking on save button. File is not downloading.

        my code is:

        FirefoxOptions options = new FirefoxOptions()
        .addPreference(“browser.startup.page”, 1)
        .addPreference(“browser.startup.homepage”, “https://filehippo.com/download_avast_antivirus/”);
        options.addPreference(“browser.helperApps.neverAsk.openFile”, “application/octet-stream”);

        1. Hi Shushma,

          Mozilla team is not interested to set mime type of application/octet-stream in browser profile because of security threat. You can check this link https://bugzilla.mozilla.org/show_bug.cgi?id=201546 for more understanding…

          1. shushma says:

            Thank you..

  5. swagatika says:

    Hi mukesh ,

    can you please clarifye ,

    in line number 16 , why you mentioned “application/octet-stream” is it a file type ?

    1. Hi Sangeetha,

      Hope this link will help you to understand it

    2. Hi Swagatika,

      Hope this link will help you to understand it

  6. Dhanashree says:

    Hi Mukesh ,
    How to handle pdf controls like (Zoom in , Zoom out ) . Can you please help me ? Can you share me java code for reference .

    1. Hi Dhanashree,

      Handling controls like zoom in / zoom out lies with api of native application which you are using to open pdf file. Its nowhere related to Selenium.

  7. Divya Agnihotri says:

    I am getting an error in following line
    WebDriver driver = new FirefoxDriver(profile);

    Error is “TThe constructor FirefoxDriver(FirefoxProfile) is undefined”
    Please help.

    1. Hi Divya,

      Which version of Selenium are you using?

  8. manoj kumar sahoo says:

    i am not able to save a file.could you please upload the video of it?

    1. Hi Manoj,

      I will post it soon.

  9. Sowmyashree R says:

    On clicking on Export in my application, I get a pop up asking to Open or Save file. How to open or save a file and check whether expected file exists, please explain…

    1. Sowmyashree R says:

      Please explain for Chrome and IE

      1. I will upload soon.

    2. Hi Sowmya,

      Code will download the file then you can write java program to check whether file exist or not after downloading.

      1. Sowmyashree R says:

        Thanks Mukesh, could you please share the code

        1. Hi Sowmyashree,

          Please keep patience, very soon I’ll post a video for this.

  10. sonali says:

    how to download files using chrome browser

    1. Hi Sonali,

      I will upload soon.

  11. Tarun says:

    Hi Mukesh,

    I would like to change default download dir for Chrome? How do you set capabilities in browser?

    Following is my code. It sets default download path but it pop up dialog box to save file. Any help is appreciated.

    Map chromePrefs = new HashMap();
    chromePrefs.put(“profile.default_content_settings.popups”, 2);
    chromePrefs.put(“download.default_directory”, getFilePath());
    ChromeOptions options = new ChromeOptions();
    //Map chromeOptionsMap = new HashMap();
    options.setExperimentalOption(“prefs”, chromePrefs);
    options.addArguments(“–test-type”);

    capability = DesiredCapabilities.chrome();
    capability.setCapability(“chrome.switches”, Arrays.asList(“–start-maximized,–ignore-certificate-error”));
    capability.setCapability(ChromeOptions.CAPABILITY, options);
    //capability.setCapability(ChromeOptions.CAPABILITY, chromeOptionsMap);

    1. is this fixed Tarun?

  12. Lavina says:

    Hi Mukesh,

    After clicking on Download icon, i am getting a popup window having options ‘open with’ , ‘save file’ & there are two options at the bottom of popup window having ‘OK’ or ‘Cancel’ option.
    I just want to click on download icon(Which i am able to do) but then i want to cancel it from popup & don’t want to open or save it.
    How do i achieve it?

    1. Hi Lavina is this fixed?

  13. suresh says:

    hii, mukesh ur teaching is excellent

  14. shilpa says:

    Hi Mukesh,

    I want to check “downloading pdf” files. But I have to write script with Ruby. And I dont have much experience in Ruby. Can you plz help there?

    1. Hi Shilpa,

      Not sure on Ruby 🙁

  15. Sreenath says:

    Hi Mukesh ,

    This code is for Mozilla Firefox, how to do this in Chrome/IE

  16. Priyanka Chouhan says:

    I becomes fan of urs..great way of explaining thing.. I m new to selenium..your post really helpful for me.. Thankyou

    1. Hey Priyanka,

      🙂 Your comment made my day. Thank you so much. keep in touch and let me know if any help required in Selenium.

  17. Vasu says:

    Hi Mukesh,
    Loved your way of explaining the things. 🙂
    here i’ve a doubt on downloading files
    If we follow the way of configuring all the MIME types we require in the Firefox browser, it never never pops up a download but how can we ensure whether file downloading happening or not?(There could be a chance of getting a bugs like below
    1.Even if selenium clicks no file gets downloaded. 2.There could be page redirection sometimes
    3. Redirects to an error page)
    So what i feel is like firing an robot class event on the buttons like ‘Ok’ or ‘cancel’ on the download window so that we can ensure file downloading happening.

    1. Yes Vasu correct and you can follow robot class as well. My main intention was to handle download option because it may stop the execution.

  18. Suresh Sharma says:

    Hi Mukesh,
    same is working fine. when i run via eclipse–>testng.xml–>RunasTestSuite but same script is not working with Jenkins.
    Moreover i created sikuli script for the same and skiuli script is also working fine with eclipse but not with jenkins.
    I am running jenkins as windows’ service.
    pls suggest!!

    1. Hey Suresh,

      Strange 🙁 Can you tell me what exception it generate while running via Jenkins.

      Note- if jenkins runs in headless mode then Sikuli won’t work.

  19. Learner says:

    The above code is not working for .pdf files. i have used

    profile.setPreference(“browser.helperApps.neverAsk.saveToDisk”, “application/pdf”);

    profile.setPreference(“browser.helperApps.neverAsk.openFile”, “application/pdf”);

    Everytime the pop up window appears to ask to save or open the file when eclipse open the browser, however when I open the browser manually and click on download the file it automatically download the file without any pop ups.

    1. Hi Kopal,

      Please use Sikuli for this now 🙂

  20. divakar says:

    Superb explanation!!!!!

    1. Thanks Divakar 🙂 Keep visiting.

  21. Nitin says:

    Beautiful!! Thanks for sharing the same!! 🙂

  22. vivek says:

    thanks…

  23. sivakrishna says:

    hi mukesh

    i have already created webdriver object for my previous testscripts,so only for pdf download if i create another driver object like above is it good ?
    other wise how can i set the fire fox profile for the existing driver object.

    bcoz i am using jbehave with serenity.
    plz reply me asap…
    hope u understand my problem

    Thanks&Regards,
    Krishna

    1. Hi Siva,

      I would suggest add all the MIME type in firefox profile which are mostly used in application like pdf,.exe,word etc.

  24. QualityAnalyst says:

    I tried for downloading excel file but didn’t work.
    Here is my code,

    @Before
    public void setUp() throws Exception {

    FirefoxProfile profile=new FirefoxProfile();
    profile.setPreference(“browser.helperApps.neverAsk.saveToDisk”, “D://App_Downloads/x-excel”);

    driver=new FirefoxDriver(profile);
    baseUrl = “http://cschool.co”;
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

    }

    @Test
    public void testCase02() throws Exception {
    driver.get(baseUrl + “/admin/”);
    driver.manage().window().maximize();

    driver.findElement(By.cssSelector(“button.saveButton”)).click();
    driver.findElement(By.linkText(“Download”)).click();
    Thread.sleep(3000);

    Robot object=new Robot();
    object.keyPress(KeyEvent.VK_ENTER);
    }
    Please help me out!

    1. Make the below changes and run again

      profile.setPreference(“browser.helperApps.neverAsk.saveToDisk”, “application/excel”);

  25. sateesh says:

    What is the mime type for .apk(Android APP Apk ) file or .ipa (IOS APP ipa)file
    ….here i’m trying to download the .apk (android apk file) file, i was stucked at download dialog box where i’m unable to click on save button.

    1. Hi Sateesh,

      try below MIME type application/vnd.android.package-archive

  26. Omprakash says:

    i have tried above process for Jpeg and tiff format files. but is not working

    1. Hi Omprakash,

      Have you changed the MEMI type of jpeg file because this is working code and I use this frequently in my application.

      Can u please check ur code again?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.