How To Download Different Files Using Selenium WebDriver

In my PREVIOUS POST, We have learnt about how to create and use custom profile of Firefox browser to use It In selenium webdriver software automation test. Now let me show you how to create Firefox custom profile run time and set Its properties to download any file using selenium webdriver software testing tool. Many times you need to download different files from software web application like MS Excel file, MS Word File, Zip file, PDF file, CSV file, Text file, ect..

It Is tricky way to download file using selenium webdriver software testing tool. Manually when you click on link to download file, It will show you dialogue to save file In your local drive as shown In bellow given Image.

Now selenium webdriver software automation testing tool do not have any feature to handle this save file dialogue. But yes, Selenium webdriver has one more very good feature by which you do not need to handle that dialogue and you can download any file very easily. We can do It using webdriver's Inbuilt class FirefoxProfile and Its different methods. Before looking at example of downloading file, Let me describe you some thing about file's MIME types. Yes you must know MIME type of file which you wants to download using selenium webdriver software testing tool.

What Is MIME of File
MIME Is full form of Multi-purpose Internet Mail Extensions which Is useful to Identify file type by browser or server to transfer online.

You need to provide MIME type of file In your selenium webdriver test so that you must be aware about It. There are many online tools available to know MIME type of any file. Just google with "MIME checker" to find this kind of tools.

In our example given bellow, I have used MIME types as shown bellow for different file types In bellow given selenium webdriver test.

  1. Text File (.txt) - text/plain
  2. PDF File (.pdf) - application/pdf
  3. CSV File (.csv) - text/csv
  4. MS Excel File (.xlsx) - application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
  5. MS word File (.docx) - application/vnd.openxmlformats-officedocument.wordprocessingml.document
Example Of downloading different files using selenium webdriver

package Testng_Pack;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class downloadingfile {
 WebDriver driver;
 
 @BeforeTest
 public void StartBrowser() {
  //Create object of FirefoxProfile in built class to access Its properties.
  FirefoxProfile fprofile = new FirefoxProfile();
  //Set Location to store files after downloading.
  fprofile.setPreference("browser.download.dir", "D:\\WebDriverdownloads");
  fprofile.setPreference("browser.download.folderList", 2);
  //Set Preference to not show file download confirmation dialogue using MIME types Of different file extension types.
  fprofile.setPreference("browser.helperApps.neverAsk.saveToDisk", 
    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;"//MIME types Of MS Excel File.
    + "application/pdf;" //MIME types Of PDF File.
    + "application/vnd.openxmlformats-officedocument.wordprocessingml.document;" //MIME types Of MS doc File.
    + "text/plain;" //MIME types Of text File.
    + "text/csv"); //MIME types Of CSV File.
  fprofile.setPreference( "browser.download.manager.showWhenStarting", false );
  fprofile.setPreference( "pdfjs.disabled", true );
  //Pass fprofile parameter In webdriver to use preferences to download file.
  System.setProperty("webdriver.gecko.driver", "D:\\Selenium Files\\geckodriver.exe");
  driver = new FirefoxDriver(fprofile);  
 } 
 
 @Test
 public void OpenURL() throws InterruptedException{
  driver.get("http://only-testing-blog.blogspot.com/2014/05/login.html");
         //Download Text File
  driver.findElement(By.xpath("//a[contains(.,'Download Text File')]")).click();
  Thread.sleep(5000);//To wait till file gets downloaded.
                //Download PDF File
  driver.findElement(By.xpath("//a[contains(.,'Download PDF File')]")).click();
  Thread.sleep(5000);
                //Download CSV File
  driver.findElement(By.xpath("//a[contains(.,'Download CSV File')]")).click();
  Thread.sleep(5000);
                //Download Excel File
  driver.findElement(By.xpath("//a[contains(.,'Download Excel File')]")).click();
  Thread.sleep(5000);
                //Download Doc File
  driver.findElement(By.xpath("//a[contains(.,'Download Doc File')]")).click();
  Thread.sleep(5000);  
 }
 
 @AfterTest
 public void CloseBrowser() {  
  driver.quit();  
 }
}

When you run above example, It will download all 5(Text, pdf, CSV, docx and xlsx) files one by one and store them In D:\WebDriverdownloads folder automatically as shown In bellow given example.



InterruptedException Is used with method OpenURL to handle checked exception of Thread.sleep(5000). View detailed tutorials of exception handling In selenium WebDriver software test automation on THIS LINK.

This way you can download any file using selenium webdriver like zip file, exe file, etc.. Just know your file's MIME type and download It as shown In above example.

23 comments:

  1. You are doing excellent and gr8 work!
    please let me know how to download file using chrome and IE.

    Thank you in advance!

    ReplyDelete
  2. The way u'r explaining each & every topic is really superb.
    Thanks a lot Arvind.

    ReplyDelete
  3. Hi Arvind,

    I'm trying to download the CSV file. I got two problems

    1. When I use your code..I got java complaining "Cannot instantiate the type WebDriver" on this code .. driver = new WebDriver(fprofile);

    2. I got a Null pointer Exception on OpenURL

    ReplyDelete
    Replies
    1. Hi Edward,

      You can't create object for the interface WebDriver

      Delete
    2. You need to say
      driver = new FirefoxDriver(fprofile);

      Delete
  4. fprofile.setPreference("browser.download.folderList", 2);
    what does value 2 refrer

    ReplyDelete
    Replies
    1. 2 - download to custom folder path
      0 - download to desktop

      Delete
  5. Solution doesn't work for "Default" firefox profile

    Any workaround ??

    ReplyDelete
  6. setPreference("browser.download.folderList", 2);
    Default Value: 1
    The value of browser.download.folderList can be set to either 0, 1, or 2. When set to 0, Firefox will save all files downloaded via the browser on the user's desktop. When set to 1, these downloads are stored in the Downloads folder. When set to 2, the location specified for the most recent download is utilized again.

    ReplyDelete
  7. HI. After hours of digging in internet finally your post helps solve my problem. If someone want to do it in RobotFramework with Selenium2Library:

    from Selenium2Library import Selenium2Library
    from selenium.webdriver import FirefoxProfile

    fprofile= FirefoxProfile()
    fprofile.set_preference("browser.download.dir", "D:\\WebDriverdownloads");
    fprofile.set_preference("browser.download.folderList", 2);
    fprofile.set_preference("browser.helperApps.neverAsk.saveToDisk","application/pdf;" );
    fprofile.set_preference( "browser.download.manager.showWhenStarting", False );
    fprofile.set_preference( "pdfjs.disabled", True );

    sel=Selenium2Library()
    sel.create_webdriver('Firefox',firefox_profile=fprofile)

    Thank you

    ReplyDelete
    Replies
    1. Hi ,

      I am trying same thing but not working.
      Can you provide complete code for that?

      Delete
  8. Hi Arvind,

    This is not working for me. I am using the exact piece of code but the dialogue box again pops up :( Kindly help. What could i be missing here?

    Thanks!

    ReplyDelete
  9. I was able to verify the code:
    using selenium web driver all files were downloaded automatically.
    using manual download, download prompts dialog.

    But let me correct the 2nd sentence.
    Not all files... PDF still prompts dialog.

    ReplyDelete
  10. Solved my problem. Thanks for this solution and your blog post!

    ReplyDelete
  11. I tried, for me it works only for XLS but NOT for XLSX, any ideas?

    ReplyDelete
  12. Hey guys,

    Use the following link and get the Required MIME types and use it in your code..

    http://www.freeformatter.com/mime-types-list.html

    ReplyDelete
  13. What is the purpose of these two lines,can anyone please explain ?
    fprofile.setPreference( "browser.download.manager.showWhenStarting", false );
    fprofile.setPreference( "pdfjs.disabled", true );

    ReplyDelete
  14. Hey Arvind,

    I phase some problem in downloading the pdf and html files. The problem is that there is a single div and this div consists lots of sections. But I want data only from section 1. But section 1 is written in a single h4 tag , section 2 is written in a single h4 tag like that. when I give the xpath its getting download all the files not only from xpath.

    ReplyDelete
  15. Hi Guys,

    Need Help. I want to downlaod a pdf file & save it in desired location
    Scenario - After i Click of Generate Button A New window/Page(Pdf page) appears & then it contains a download button if i click on download button it should download to a certain location
    Kindly give a code

    ReplyDelete