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<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); // 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:
<properties>
<!-- Remove encoding warnings -->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-server -->
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-server</artifactId>
<version>3.141.59</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.6.2</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-compiler-plugin -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<release>11</release>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
</plugin>
</plugins>
</build>
For Chromedriver try out with:
String downloadFilepath = "/path/to/download";
HashMap<String, Object> chromePrefs = new HashMap<String, Object>();
chromePrefs.put("profile.default_content_settings.popups", 0);
chromePrefs.put("download.default_directory", downloadFilepath);
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("prefs", chromePrefs);
DesiredCapabilities cap = DesiredCapabilities.chrome();
cap.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
cap.setCapability(ChromeOptions.CAPABILITY, options);
WebDriver driver = new ChromeDriver(cap);
Note:- In windows you need to use \\ for path while if you are using linux or mac then use //
Hope this helps. :)
For Chrome driver, the below code is worked for me
String downloadFilepath = "/path/to/download";
HashMap<String, Object> chromePrefs = new HashMap<String, Object>();
chromePrefs.put("profile.default_content_settings.popups", 0);
chromePrefs.put("download.default_directory", downloadFilepath);
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("prefs", chromePrefs);
WebDriver driver = new ChromeDriver(options);
The ans which help me to resolve this issue on windows (https://bugs.chromium.org/p/chromedriver/issues/detail?id=783).
Map<String, Object> prefs = new HashMap<String, Object>();
prefs.put("download.default_directory", System.getProperty("user.dir")+ File.separator + "externalFiles" + File.separator + "downloadFiles");
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("prefs", prefs);
ChromeDriver driver = new ChromeDriver(options);
To make it more clean and easy, I developed a library which lets you generate a ChromeOptions object which contains your download folder in one line. For example, to define "/tmp/downloads", use:
private SeleniumDownloadKPI seleniumDownloadKPI;
@BeforeEach
void setUpTest() {
// New instance of SeleniumDownloadKPI with given download folder.
seleniumDownloadKPI =
new SeleniumDownloadKPI("/tmp/downloads");
ChromeOptions chromeOptions =
seleniumDownloadKPI.generateDownloadFolderCapability();
driver = new ChromeDriver(chromeOptions);
The library also contains methods which allow to receive download KPI and perform assertion.
For Python users who see this page -- here's how I set the download directory in Python Selenium (this is just the Python version of Shubham's accepted answer):
def newChromeBrowser(headless=True, downloadPath=None):
""" Helper function that creates a new Selenium browser """
options = webdriver.ChromeOptions()
if headless:
options.add_argument('headless')
if downloadPath is not None:
prefs = {}
os.makedirs(downloadPath)
prefs["profile.default_content_settings.popups"]=0
prefs["download.default_directory"]=downloadPath
options.add_experimental_option("prefs", prefs)
browser = webdriver.Chrome(chrome_options=options, executable_path=CHROMEDRIVER_PATH)
return browser