Please find the below code with the chrome capabilities. In fact the browser is not downloading the file to the specified path.
private static DesiredCapabi
Chrome: v84
ChromeDriver: v83
JDK: OpenJDK 11 (LTS)
Use Paths class for platform-independent file separators.
@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();
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); // ChromeDriver binary is added to PATH env var
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();
}
Output:
Doing mvn clean prior to any run also takes care of having to override existing files.
pom.xml:
UTF-8
UTF-8
org.seleniumhq.selenium
selenium-server
3.141.59
test
org.junit.jupiter
junit-jupiter
5.6.2
test
org.apache.maven.plugins
maven-compiler-plugin
3.8.1
11
org.apache.maven.plugins
maven-surefire-plugin
2.22.2