使用Selenium Webdriver更改Google Chrome中的下载位置

时间:2014-06-02 13:13:47

标签: selenium-webdriver

我尝试过以下代码:

ChromeOptions profile=new ChromeOptions();
profile.addArguments("disable-popup-blocking", "true");
profile.addArguments("download.default_directory","D:\\WORKSPACE\\SeConnect\\Downloads\\");
profile.addArguments("download.directory_upgrade", "true");
profile.addArguments("download.prompt_for_download", "false");
driver = new ChromeDriver(profile);

但它没有设定路径。它使用默认路径。

1 个答案:

答案 0 :(得分:0)

driver.get("chrome://settings/advanced");
            JavascriptExecutor js = (JavascriptExecutor) driver;
            String prefId = "download.default_directory";
            File tempDir=new File(System.getProperty("user.dir")+"\\Downloads\\");
            if (driver.findElements(By.xpath(String.format(".//input[@pref='%s']", prefId))).size() == 0) {
                driver.get("chrome://settings-frame");
                driver.findElement(By.xpath(".//button[@id='advanced-settings-expander']")).click();
            }
            String tmpDirEscapedPath = tempDir.getCanonicalPath().replace("\\", "\\\\");
            js.executeScript(String.format("Preferences.setStringPref('%s', '%s', true)", prefId,
                    tmpDirEscapedPath));