JAVA Selenium Webdriver 下载前询问每个文件的保存位置

标签 java selenium browser selenium-webdriver

我正在尝试使用 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/

相关文章:

java - 如何检测 SWT 对话框已打开并且可见?

Java 图形 : setClip vs clipRect vs repaint(int, 整数、整数、整数)

java - isDisplayed() 与 Selenium 中的 isVisible()

javascript - 是否可以在浏览器中实现任何类型的文件上传恢复/恢复?

javascript - 如何判断JS代码在浏览器中是否正常运行?

java - Dozer - 排除嵌套对象

java - eclipse : Import maven project into current workspace location

python - 可以设置接受语言 header 但不能设置连接 header 吗? PhantomJS(带有 Python 的 Selenium Webdriver)

java - 如何使用独立/容器化服务器运行 Selenium 测试

javascript - 使用 javascript 添加图像后浏览器滚动条移动