Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to download any file and save it to the desired location using Selenium Webdriver

I have to perform following task using Selenium Webdriver given below.

  1. Click on any link/button that start downloading any file (filetype may be anything image, pdf, jar etc)
  2. Click on the "Save" on popup if appeared (e.g. in case of http://selenium.googlecode.com/files/selenium-server-standalone-2.33.0.jar)
  3. Give the desired location to save that file.

Can anyone share, how can we implement this using Java?

like image 902
Sankumarsingh Avatar asked May 25 '13 05:05

Sankumarsingh


People also ask

How do I change the default download location in Selenium?

We can change the setting manually, but it gets modified on triggering a script. We change the directory for download in Chrome browser with the help of ChromeOptions class. We are required to add capabilities to the browser with the parameter download. default_directory.

Which WebDriver method is used to provide the file location to a file upload dialog?

Uploading files in WebDriver is done by simply using the sendKeys() method on the file-select input field to enter the path to the file to be uploaded.

Can we upload/download file using Selenium?

The most basic way of uploading files in Selenium is using the sendKeys method. It is an inbuilt feature for file upload in Selenium.


2 Answers

You won't be able to access the save dialog box. That's controlled by the OS. The only thing you're really going to be able to do is set the default download location for the browser and allow it to automatically download the files. Then check the file in Java.

You should check this answer from this previous SO question. Basically when setting up your Firefox profile you add a call to set the property browser.helperApps.neverAsk.saveToDisk to a comma separated list of MIME types to always download:

firefoxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk","text/csv"); 

See this Mozilla KB FAQ article on About:configs.

UPDATE It looks like this may now be possible see this answer in another question

like image 176
Dirk Avatar answered Sep 20 '22 08:09

Dirk


The Cancel/Save dialogue popup may be appearing because the site is sending you a different MIME type.

Check the actual header content.

Using the firefox built in Developer tools, Right click to inspect the element/download link your posting then take a look at the Network monitor to see the ContentType header value returned.. That would be the one you want to use..

enter image description here

Set your profile settings accordingly

 firefoxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk",                      "application/octet-stream,text/csv"); 

I was expecting "text/csv" however got "application/octet-stream" once that was added to the accepted types list it all worked as expected, No popups

like image 38
Abelgo Avatar answered Sep 24 '22 08:09

Abelgo