Wednesday, July 17, 2013

How to download a file in WebDriver

Here's a solution. Set Firefox's preferences to save automatically, and not have the downloads window popup. Then you just grab the file, and it'll download.

import java.io.File;

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.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

public class TestCase {
   
    FirefoxProfile firefoxProfile = null;
    WebDriver driver = null;
   
    @BeforeClass(alwaysRun=true)
    public void setUp(){
        File downloadDir = new File("c:\\downloads");
        if (!downloadDir.exists()){
            downloadDir.mkdir();
        }
    }
   
    @BeforeMethod
    public void beforeMethod() {
        firefoxProfile = new FirefoxProfile();
        firefoxProfile.setPreference("browser.download.folderList",2);
        firefoxProfile.setPreference("browser.download.manager.showWhenStarting",false);
        firefoxProfile.setPreference("browser.download.dir","c:\\downloads");
        firefoxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk","image/jpg, text/csv,text/xml,application/xml,application/vnd.ms-excel,application/x-excel,application/x-msexcel,application/excel,application/pdf");       
    }
   
    @Test
    public void downloadFile(){
        driver = new FirefoxDriver(firefoxProfile);
        driver.get("http://support.vendhq.com/entries/21265746-Sample-CSV-file-to-upload-into-trial-account");
        driver.findElement(By.linkText("vend_products_31Aug12.csv")).click();
        driver.close();
    }
}

 Note:
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.