我正在尝试使用 Selenium 自动下载文件。
每当收到要下载的文件时,我都想将该特定文件保存到自定义位置并使用自定义名称保存。
我希望浏览器要求保存每个文件,以便我可以动态提供自定义路径和文件名。
我可以将文件保存到自定义目录,但无法控制文件名。我想使用 java.awt.Robot、java.awt.datatransfer.StringSelection 和 java.awt.Toolkit 来使用自定义文件名。
My code
ChromeOptions chromeOptions = new ChromeOptions();
HashMap<String, Object> chromePreferences = new HashMap<String, Object>();
chromePreferences.put("profile.default_content_settings.popups", 0);
chromePreferences.put("download.default_directory", browserDownloadDirectoryPath);
chromePreferences.put("safebrowsing.enabled", "true");
chromeOptions.setExperimentalOption("prefs", chromePreferences);
chromeOptions.addArguments("--test-type");
chromeDesiredCapabilities = DesiredCapabilities.chrome();
chromeDesiredCapabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions);
这会将文件保存到自定义文件夹。
如果浏览器要求保存文件,我想使用Robot Class来发送路径。
StringSelection stringSelection = new StringSelection(
"<file path>" + "<file name>");
Toolkit.getDefaultToolkit().getSystemClipboard()
.setContents(stringSelection, null);
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_TAB);
robot.keyRelease(KeyEvent.VK_TAB);
robot.keyPress(KeyEvent.VK_DOWN);
robot.keyRelease(KeyEvent.VK_DOWN);
robot.keyPress(KeyEvent.VK_DOWN);
robot.keyRelease(KeyEvent.VK_DOWN);
robot.keyPress(KeyEvent.VK_TAB);
robot.keyRelease(KeyEvent.VK_TAB);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
请提供强制浏览器要求保存文件的解决方案。
对于 Firefox,我们有 about:config
来查看浏览器的所有首选项。我们对于其他浏览器也有类似的东西吗?
最佳答案
更好的方法是设置 chrome 自动下载文件,然后等待新文件出现,最后重命名。
以下是通过单击链接下载 PDF 并将其重命名为“mydocument.pdf”的示例:
// define the download folder
Path download_folder = Paths.get(System.getProperty("user.home") + "/Downloads");
// define the preferences
HashMap<String, Object> prefs = new HashMap<String, Object>();
prefs.put("download.default_directory", download_folder.toAbsolutePath());
prefs.put("download.prompt_for_download", false);
prefs.put("download.directory_upgrade", true);
prefs.put("plugins.plugins_disabled", new String[]{"Chrome PDF Viewer"});
// define the options
HashMap<String, Object> options = new HashMap<String, Object>();
options.put("prefs", prefs);
// define the capabilities
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability("chromeOptions", options);
// start the driver
WebDriver driver = new ChromeDriver(capabilities);
// click on a PDF link
driver.get("http://www.adobe.com/legal/terms.html");
driver.findElement(By.linkText("Adobe Creative SDK")).click();
// wait for the PDF to be downloaded
File file = WaitForNewFile(download_folder, ".pdf", 60);
// rename the downloaded file
file.renameTo(download_folder.resolve("mydocument.pdf").toFile());
// quit
driver.quit();
对于文件服务员:
/**
* Waits for a new file to be downloaded with a file watcher
*/
public static File WaitForNewFile(Path folder, String extension, int timeout_sec) throws InterruptedException, IOException {
long end_time = System.currentTimeMillis() + timeout_sec * 1000;
try (WatchService watcher = FileSystems.getDefault().newWatchService()) {
folder.register(watcher, StandardWatchEventKinds.ENTRY_MODIFY);
for (WatchKey key; null != (key = watcher.poll(end_time - System.currentTimeMillis(), TimeUnit.MILLISECONDS)); key.reset()) {
for (WatchEvent<?> event : key.pollEvents()) {
File file = folder.resolve(((WatchEvent<Path>)event).context()).toFile();
if (file.toString().toLowerCase().endsWith(extension.toLowerCase()))
return file;
}
}
}
return null;
}
关于JAVA Selenium Webdriver 下载前询问每个文件的保存位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36842428/