JAVA Selenium Webdriver在下载之前询问保存每个文件的位置 [英] JAVA Selenium Webdriver Ask where to save each file before downloading

查看:252
本文介绍了JAVA Selenium Webdriver在下载之前询问保存每个文件的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Selenium自动下载文件。

I am trying to automate file download using Selenium.

每当收到要下载的文件时,我想将该特定文件保存到自定义位置并保存自定义名称。

Whenever a file is received for download, i want to save that particular file to custom location and save it with custom name.

我希望浏览器要求保存每个文件,以便我可以动态提供自定义路径和文件名。

I want browser to ask to save each file so that i can provide custom path and file name dynamically.

我能够将文件保存到自定义目录,但我无法控制文件名。我想使用 java.awt.Robot java.awt.datatransfer.StringSelection java.awt.Toolkit 用于使用自定义文件名。

I am able to save the file to custom directory but i could not get control on the file name. I want to use java.awt.Robot, java.awt.datatransfer.StringSelection and java.awt.Toolkit for using custom file name.


我的代码

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);

这是将文件保存到自定义文件夹。

This is saving file to custom folder.

如果浏览器要求保存文件,我想使用Robot Class发送路径。

If the browser ask for file saving, i want to use Robot Class to send path.

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);

请提供强制浏览器请求保存文件的解决方案。

Kindly provide a solution to force browser to ask to save file.

对于Firefox,我们有 about:config 来查看浏览器的所有首选项。我们也为其他浏览器提供类似的东西吗?

For Firefox, we have about:config to see all preferences for the browser. Do we have something like this for other browsers as well?

推荐答案

更好的方法是设置chrome以自动下载文件,然后等待新文件出现并最终重命名。

A better way would be to setup chrome to automatically download the file, then wait for a new file to appear and finally rename it.

以下是通过单击链接下载PDF然后将其重命名为mydocument的示例。 pdf:

Here is an example to download a PDF by clicking on a link and then rename it to "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在下载之前询问保存每个文件的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆