简体   繁体   中英

How to set Safari download location - Selenium WebDriver

Trying to set safari (driver) download directory to specific location. Now it will just download files to default "Downloads" folder.

String currentDirectory = System.getProperty("user.dir");
String downloadFilePath = currentDirectory+"/download/";

Already tried:

dc.setCapability("safari.download.dir", downloadFilePath);
dc.setCapability("browser.download.dir", downloadFilePath);
dc.setCapability("safari.options.dataDir", downloadFilePath); // ("safari.options.dataDir" // this part won't work)

safariOptions.setCapability("safari.options.dataDir", downloadFilePath);

safariPrefs.put("download.deafult_directory", downloadFilePath); // this one I am using for chromedriver (chromePrefs)

Well, you can try to use an HTTP connection to download the file! That way, you can for sure have it saved to the directory specified in your variable.

Most languages have APIs (or libraries) for performing HTTP requests. For example, to accomplish this in Java, you could use URL.openConnection()

String link = linkElement.getAttribute("href");
URL url = new URL(link);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");

Then you can use HttpURLConnection.getInputStream() to write the file contents to your preferred location.

try (InputStream in = httpURLConnection.getInputStream()) {
    Files.copy(in, new File("/path/to/file.ext").toPath(),
        StandardCopyOption.REPLACE_EXISTING);
}

ONLY IN CASE YOU ARE USING COOKIES: You can add them to your HTTP connection. If in this case, you must use a password saved on your cookies, this can be very useful.

Set<Cookie> cookies = webDriver.manager().getCookies();
String cookieString = "";

for (Cookie cookie : cookies) {
    cookieString += cookie.getName() + "=" + cookie.getValue() + ";";
}

httpURLConnection.addRequestProperty("Cookie", cookieString);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM