带有Chrome的Selenium Java下载文件到特定目录

时间:2019-06-03 11:26:05

标签: java automated-tests

我指出了下载文件的路径,但是文件下载到另一个方向。

我的Chrome浏览器属性:

File file = new File("./src/drivers/chromedriver" + (isWindows ? ".exe" : ""));
        String downloadFilepath = ".\\src\\test\\resources\\downloads";
        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);
        System.setProperty("webdriver.chrome.driver", file.getAbsolutePath());

我使用方法指示说明并从文件夹中删除文件:

public boolean isFileDownloaded(String downloadPath, String fileName) {
    File dir = new File(downloadPath);
    File[] dirContents = dir.listFiles();
    for (int i = 0; i < dirContents.length; i++) {
        if (dirContents[i].getName().equals(fileName)) {
            // File has been found, it can now be deleted:
            dirContents[i].delete();
            return true;
        }
    }
    return false;
}

此外,我在高级方法中指示路径和文件名:

public void isSomeFileDownloaded(){
  actions.isFileDownloaded("src\\test\\resources\\downloads","SomeFile.pdf");
}

但是文件保存到另一个方向-这是默认的Chrome浏览器下载方向。 我还使用了Not able to download file in chrome(59 Latest) to a specific directory without any window popup using Selenium WebDriver的推荐 但问题仍然存在 我做错了什么? 预先感谢。

1 个答案:

答案 0 :(得分:0)

在Windows上,尝试使用此功能:

Map<String, Object> prefs = new HashMap<String, Object>();
prefs.put("download.default_directory",System.getProperty("user.dir") + File.separator + "externalFiles" + File.separator + "downloadFiles");   
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("prefs", prefs);
ChromeDriver driver = new ChromeDriver(options);