Thursday, August 6, 2015

Selenium WebDriver - Code to save file on preferred location

In case of Chrome Browser:

                System.setProperty("webdriver.chrome.driver", "path\\chromedriver.exe");
String downloadFilepath = "path_location";
HashMap chromePrefs = new HashMap();
chromePrefs.put("profile.default_content_settings.popups", 0);
chromePrefs.put("download.default_directory", downloadFilepath);
ChromeOptions options = new ChromeOptions();
HashMap chromeOptionsMap = new HashMap();
options.setExperimentalOption("prefs", chromePrefs);
options.addArguments("--test-type");
DesiredCapabilities cap = DesiredCapabilities.chrome();
cap.setCapability(ChromeOptions.CAPABILITY, chromeOptionsMap);
cap.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
cap.setCapability(ChromeOptions.CAPABILITY, options);
WebDriver driver = new ChromeDriver(cap);

//This will work for all cases mentioned above
driver.get("http://docs.seleniumhq.org/download/");
driver.findElement(By.xpath("html/body/div[1]/div[2]/div[2]/p[6]/a[1]")).click();


In case of FireFox Browser:

// Code to download file at specific path
FirefoxProfile prof = new FirefoxProfile();
prof.setPreference("browser.download.folderList", 2);
prof.setPreference("browser.download.manager.showWhenStarting",false);
prof.setPreference("browser.download.dir", path);
prof.setPreference("browser.helperApps.neverAsk.saveToDisk",
"application/zip, text/html, application/xhtml+xml, application/xml, application/csv, text/plain, application/vnd.ms-excel, text/csv, text/comma-separated-values, application/octet-stream");

//This will work for all cases mentioned above
driver.get("http://docs.seleniumhq.org/download/");
driver.findElement(By.xpath("html/body/div[1]/div[2]/div[2]/p[6]/a[1]")).click();

No comments:

Post a Comment