Download a file in Selenium WebDriver using Java

In this blogpost, we are going to automate file download functionality using WebDriver with Java.

Note : We are not going to use any third party tool like AutoIT to achieve our goal.

We can make use of FirefoxProfile class to set the various preferences related to downloading of a file, and configure the driver instance with already set preferences.

Have a look at the working demo of file download functionality.

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;

public class FileDownloadDemo {

             public static void main(String[] args) {
                        FirefoxProfile fprofile = new FirefoxProfile();
                        fprofile.setPreference(“browser.download.dir”, “C:\\Users\\User\\Desktop”);
                        fprofile.setPreference(“browser.download.folderList”, 2);

                        fprofile.setPreference(“browser.helperApps.neverAsk.saveToDisk”,
“application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;” + “application/pdf;”
+ “text/plain;” + “text/csv;”);

 

                        fprofile.setPreference(“browser.download.manager.showWhenStarting”, false);
                       fprofile.setPreference(“pdfjs.disabled”, true);

                        WebDriver driver = new FirefoxDriver(fprofile);
                       driver.get(“http://only-testing-blog.blogspot.in/2014/05/login.html”);

                      try {
                                Thread.sleep(10000);
                     } catch (InterruptedException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                     }
         

                    driver.findElement(By.xpath(“//a[contains(.,’Download Text File’)]”)).click();

                   driver.findElement(By.xpath(“//a[contains(.,’Download PDF File’)]”)).click();

                   driver.findElement(By.xpath(“//a[contains(.,’Download CSV File’)]”)).click();
               }

}

Visit Defining FirefoxProfile preferences using Selenium WebDriver with Java to know more about FirefoxProfile class and its usage.

Hope it works for you!!

Cheers 🙂

 

Advertisements

#download-file-using-selenium-webdriver, #file-download, #firefoxprofile