Skip to content

Instantly share code, notes, and snippets.

@kathyrollo
Last active March 29, 2023 09:18
Show Gist options
  • Save kathyrollo/f4d61c535b756b3b246465164a322f25 to your computer and use it in GitHub Desktop.
Save kathyrollo/f4d61c535b756b3b246465164a322f25 to your computer and use it in GitHub Desktop.
Download File with Selenium WebDriver using Paths Class
@Test
public void doFileDownload() throws Throwable {
// Since Java 7: Relative path from project root dir
// Put in target dir to avoid committing downloaded files
var downloadDir = Paths.get("target").toAbsolutePath().toString();
var prefs = new HashMap<String, Object>();
prefs.put("download.default_directory", downloadDir); // Bypass default download directory in Chrome
prefs.put("safebrowsing.enabled", "false"); // Bypass warning message, keep file anyway (for .exe, .jar, etc.)
var opts = new ChromeOptions();
opts.setHeadless(true);
opts.setExperimentalOption("prefs", prefs);
var driver = new ChromeDriver(opts);
driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.get("https://the-internet.herokuapp.com/download");
var downloadLink = driver.findElement(By.cssSelector("a[href*='some-file.txt']"));
var downloadHref = downloadLink.getAttribute("href").replace(":", "");
var downloadFileName = Paths.get(downloadHref).getFileName().toString();
downloadLink.click();
// Wait download to finish for 60s
var downloadFilePath = Paths.get(downloadDir, downloadFileName);
new WebDriverWait(driver, 60).until(d -> downloadFilePath.toFile().exists());
// Since Java 11: Read content of downloaded file
var content = Files.readString(downloadFilePath);
// Do tests with string content...
log.info("Content={}", content);
driver.quit();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment