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.
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)
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.
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.
Mukesh Otwani says
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.
Anurag says
How to do this in with ChromeDriver
Mukesh Otwani says
Hi Anurag,
Try with below code prefsMap = new HashMap();
Map
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);
Sanjay says
This is very helpful and very easy to follow. Thanks for the post.
Mukesh Otwani says
Hi Sanjay,
You’re welcome…:)
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
Mukesh Otwani says
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
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”);
Mukesh Otwani says
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…
shushma says
Thank you..
swagatika says
Hi mukesh ,
can you please clarifye ,
in line number 16 , why you mentioned “application/octet-stream” is it a file type ?
Mukesh Otwani says
Hi Sangeetha,
Hope this link will help you to understand it
Mukesh Otwani says
Hi Swagatika,
Hope this link will help you to understand it
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 .
Mukesh Otwani says
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.
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.
Mukesh Otwani says
Hi Divya,
Which version of Selenium are you using?
manoj kumar sahoo says
i am not able to save a file.could you please upload the video of it?
Mukesh Otwani says
Hi Manoj,
I will post it soon.
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…
Sowmyashree R says
Please explain for Chrome and IE
Mukesh Otwani says
I will upload soon.
Mukesh Otwani says
Hi Sowmya,
Code will download the file then you can write java program to check whether file exist or not after downloading.
Sowmyashree R says
Thanks Mukesh, could you please share the code
Mukesh Otwani says
Hi Sowmyashree,
Please keep patience, very soon I’ll post a video for this.
sonali says
how to download files using chrome browser
Mukesh Otwani says
Hi Sonali,
I will upload soon.
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);
Mukesh Otwani says
is this fixed Tarun?
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?
Mukesh Otwani says
Hi Lavina is this fixed?
suresh says
hii, mukesh ur teaching is excellent
Mukesh Otwani says
Thanks Suresh
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?
Mukesh Otwani says
Hi Shilpa,
Not sure on Ruby 🙁
Sreenath says
Hi Mukesh ,
This code is for Mozilla Firefox, how to do this in Chrome/IE
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
Mukesh Otwani says
Hey Priyanka,
🙂 Your comment made my day. Thank you so much. keep in touch and let me know if any help required in Selenium.
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.
Mukesh Otwani says
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.
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!!
Mukesh Otwani says
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.
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.
Mukesh Otwani says
Hi Kopal,
Please use Sikuli for this now 🙂
divakar says
Superb explanation!!!!!
Mukesh Otwani says
Thanks Divakar 🙂 Keep visiting.
Nitin says
Beautiful!! Thanks for sharing the same!! 🙂
Mukesh Otwani says
Thanks Nitin
vivek says
thanks…
Mukesh Otwani says
Thanks Vivek
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
Mukesh Otwani says
Hi Siva,
I would suggest add all the MIME type in firefox profile which are mostly used in application like pdf,.exe,word etc.
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!
Mukesh Otwani says
Make the below changes and run again
profile.setPreference(“browser.helperApps.neverAsk.saveToDisk”, “application/excel”);
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.
Mukesh Otwani says
Hi Sateesh,
try below MIME type application/vnd.android.package-archive
Omprakash says
i have tried above process for Jpeg and tiff format files. but is not working
Mukesh Otwani says
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?