使用Chrome无头浏览器时文件未下载

时间:2019-07-25 14:33:09

标签: java selenium google-chrome-headless

我正在使用无头Chrome驱动程序。单击文件下载选项后,在所需位置看不到任何文件。但是,下载工作正常,没有障碍。请找到我正在使用的ChromeOptions和DesiredCapabilities

DesiredCapabilities caps = DesiredCapabilities.chrome();

Map<String, Object> prefs = new HashMap<String, Object>();
prefs.put("profile.default_content_setting_values.notifications", 2);
prefs.put("profile.default_content_settings.popups", 0);
prefs.put("download.default_directory", System.getProperty("user.dir")+File.separator+"download");

ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("--headless", "window-size=1024,768", "--no-sandbox");   
chromeOptions.addArguments("--disable-dev-shm-usage"); 
    chromeOptions.setExperimentalOption("prefs", prefs);
    chromeOptions.addArguments("disable-popup-blocking");
    chromeOptions.addArguments("--disable-extensions");
    caps.setCapability(ChromeOptions.CAPABILITY, chromeOptions);

1 个答案:

答案 0 :(得分:0)

为您做了一个快速的Google搜索,并发现了https://bugs.chromium.org/p/chromium/issues/detail?id=696481,建议您使用

Page.setDownloadBehavior。如下所示:免责声明:逐字复制

                    System.setProperty("webdriver.chrome.driver", "/usr/local/bin/chromedriver");
                    ChromeOptions options = new ChromeOptions();
                    options.addArguments("--test-type");
                    options.addArguments("--headless");
                    options.addArguments("--disable-extensions"); //to disable browser extension popup

                    ChromeDriverService driverService = ChromeDriverService.createDefaultService();
                    ChromeDriver driver = new ChromeDriver(driverService, options);

                    Map<String, Object> commandParams = new HashMap<>();
                    commandParams.put("cmd", "Page.setDownloadBehavior");
                    Map<String, String> params = new HashMap<>();
                    params.put("behavior", "allow");
                    params.put("downloadPath", "//home//vaibhav//Desktop");
                    commandParams.put("params", params);
                    ObjectMapper objectMapper = new ObjectMapper();
                    HttpClient httpClient = HttpClientBuilder.create().build();
                    String command = objectMapper.writeValueAsString(commandParams);
                    String u = driverService.getUrl().toString() + "/session/" + driver.getSessionId() + "/chromium/send_command";
                    HttpPost request = new HttpPost(u);
                    request.addHeader("content-type", "application/json");
                    request.setEntity(new StringEntity(command));
                    httpClient.execute(request);
            driver.get("http://www.seleniumhq.org/download/");
            driver.findElement(By.linkText("32 bit Windows IE")).click();