【问题标题】:JAVA Selenium Webdriver Ask where to save each file before downloadingJAVA Selenium Webdriver 在下载前询问每个文件的保存位置
【发布时间】:2016-08-18 22:53:11
【问题描述】:

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

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

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

我可以将文件保存到自定义目录,但我无法控制文件名。我想使用java.awt.Robotjava.awt.datatransfer.StringSelectionjava.awt.Toolkit 来使用自定义文件名。

我的代码

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

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

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

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 来查看浏览器的所有首选项。我们是否也为其他浏览器提供了类似的功能?

【问题讨论】:

标签: java selenium browser selenium-webdriver


【解决方案1】:

为 chrome 浏览器设置所需的功能。

  String downloadFilepath = "your path to save file";
  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);

【讨论】:

    【解决方案2】:

    更好的方法是设置 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;
    }
    

    【讨论】:

    猜你喜欢
    • 2016-09-20
    • 1970-01-01
    • 2018-07-08
    • 2013-05-20
    • 1970-01-01
    • 2012-06-03
    • 2019-12-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多