java - 从 Selenium 和 chromedriver 下载文件

标签 java google-chrome selenium download

我无法让 Selenium 和 Chrome (Canary) 下载文件。 我正在使用 Java 和 Chrome 59/60(因为我的测试同时适用于 Windows 和 Linux)并且我正在尝试开始从网页下载文件。

当我在 selenium 中不设置 headless 模式时,chrome 窗口会打开并下载文件。

当我设置 --headless 标志时,chrome 窗口不会打开,下载也不会开始。

    public static void chromeDownload() throws IOException, InterruptedException{
            
            ChromeOptions options = new ChromeOptions();
            String downloadFilepath = "";
            
            if (ValidateOS.isWindows()){
                System.out.println("This is a Windows system.");
                System.setProperty("webdriver.chrome.driver", "resources\\driver\\chromedriver.exe");
                options.setBinary("C:\\Users\\Juri\\AppData\\Local\\Google\\Chrome SxS\\Application\\chrome.exe");
                downloadFilepath = "C:\\";
            } else if (ValidateOS.isUnix()){
                System.out.println("This is a Unix system.");
                System.setProperty("webdriver.chrome.driver", "resources/driver/chromedriver");
                options.setBinary("/usr/bin/google-chrome");
                downloadFilepath = "/home/juri/";
            }
            
            // Manage the download
            HashMap<String, Object> chromePrefs = new HashMap<>();
            chromePrefs.put("profile.default_content_settings.popups", 0);
            chromePrefs.put("download.default_directory", downloadFilepath);
    
            // Save Chrome Options
            HashMap<String, Object> chromeOptionsMap = new HashMap<>();
            options.setExperimentalOption("prefs", chromePrefs);
            options.addArguments("--headless --disable-gpu");
            
            DesiredCapabilities cap = DesiredCapabilities.chrome();
            cap.setCapability(ChromeOptions.CAPABILITY, chromeOptionsMap);
            cap.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
            cap.setCapability(ChromeOptions.CAPABILITY, options);
            
            ChromeDriver driver = new ChromeDriver(cap);
                    
            driver.get("http://localhost/my-test-page.html");

            driver.findElement(By.id("download")).click(); 
            Thread.sleep(5000); // wait 5 seconds for a small file to download.. yes.. I know...
            driver.quit();
        }

点击,在 GUI 模式下开始下载。在 Headless 模式下,它不会。

如何解决?

加类

我使用的是 Chrome Canary,它的 v.60 带有 --headless 功能。在没有 gui 的服务器上运行抓取器非常方便。 但是,出于同样的原因......我发现在没有 GUI 的服务器上下载 Chrome 是没有用的。 除了主要问题。开发人员,我想知道您是否认为在 Linux 服务器上安装 chrome 只是为了以 headless 模式启动它是可以的。

更新: 如果有人会读到这篇文章,我仍在寻找解决方案:/搜索结果有一些,我都试过了

最佳答案

通过调整在此链接中找到的代码解决: Download files in Java, Selenium using ChromeDriver and headless mode

对于那些想知道我的代码现在怎么样的人...

public static void chromeDownload(String address, String Headless, String DownDir) throws IOException, InterruptedException{

    ChromeOptions options = new ChromeOptions();
    String downloadFilepath = DownDir;

    if (ValidateOS.isWindows()){
        System.out.println("This is a Windows system.");
        System.setProperty("webdriver.chrome.driver", "resources\\driver\\chromedriver.exe");
        //options.setBinary("C:\\Users\\Juri\\AppData\\Local\\Google\\Chrome SxS\\Application\\chrome.exe");
        // If this is commented, the grabber will use the main Chrome
    } else if (ValidateOS.isUnix()){
        System.out.println("This is a Unix system.");
        System.setProperty("webdriver.chrome.driver", "resources/driver/chromedriver");
        options.setBinary("/usr/bin/google-chrome");
    }

    switch (Headless.toUpperCase()){
        case "TRUE":
            options.addArguments("--headless --disable-gpu");
            break;
        case "FALSE":
        default:
            options.addArguments("--window-size=1152,768");
            break;
    }
    options.addArguments("--test-type");
    options.addArguments("--disable-extension");

    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", downloadFilepath);
    params.put("cmd", "Page.setDownloadBehavior");

    commandParams.put("params", params);
    ObjectMapper objectMapper = new ObjectMapper();
    CloseableHttpClient 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(address);

    driver.findElement(By.id("download")).click(); 
    driver.quit();
}

关于java - 从 Selenium 和 chromedriver 下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44721679/

相关文章:

java - 如何处理测试用例中 Set 的随机顺序?

python 3.6 selenium webdriver 错误 X display is required for sending-keys unable to ues Xvfb

javascript - 如何在 Chrome Javascript 控制台中自动加载旧的 Facebook 消息并处理 "Temporary Failure"错误?

javascript - 防止浏览器在没有哈希值的情况下刷新时自动滚动

javascript - 聚合物 Selenium 测试访问子元素数据

java - 动态元素里面有几个 'li'

c# - 如何在 C# 中使用 Selenium WebDriver 获取当前窗口的 URL?

java - 如何在运行时获取 Java 应用程序的 PID?

java - 在 Spring Boot 中排除 Hibernate 不起作用

java - JTextArea 和 JButton。将焦点设置在按钮上