无法从 Selenium 无头地打开 Chrome

Not able to open Chrome headless from Selenium

我正在使用 maven here.Here 是我的 Selenium 代码:​​

DesiredCapabilities capb = DesiredCapabilities.chrome();
    capb.setCapability("chrome.binary","/Applications/Google Chrome.app/Contents/MacOS/Google Chrome");
    ChromeOptions options = new ChromeOptions();
    options.addArguments("--headless","--disable-gpu", "--no-sandbox","--remote-debugging-port=9222");
    capb.setCapability(ChromeOptions.CAPABILITY, options);
    System.setProperty("webdriver.chrome.driver","/Users/nitinkumar/TEST/chromedriver");
    try{
    ChromeDriver driver = new ChromeDriver(capb);
    driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
    driver.get("https://qa.cmnetwork.co");
    driver.quit();
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }

当我 运行 "mvn test" 时,它会在 GUI 模式下启动 chrome。但它应该以无头模式打开。我有 chrome vesrion 59.0, OS X yosemite(10.10.5), chrome驱动程序 2.30Selenium 3.4.0.

它不会在 GUI 模式下打开。只会打开 chrome 启动器图标。这是预期的行为。

您必须删除参数 --remote-debugging-port。这将阻止发射的无头 Chrome。所以脚本永远不会移动forward.And你会得到一个chrome not reachable错误

所以把参数改成

options.addArguments("--headless","--disable-gpu", "--no-sandbox");

另外,--no-sandbox也没有必要。根据 Official doc 只有 --headless--disable-gpu 标志就足够了

除非您安装了多个版本的 chrome,否则也不需要 DesiredCapabilities

所以无头的简单代码-chrome

    ChromeOptions options = new ChromeOptions();
    options.addArguments("--headless","--disable-gpu");
    System.setProperty("webdriver.chrome.driver","/Users/nitinkumar/TEST/chromedriver");

    ChromeDriver driver = new ChromeDriver(options);
    driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
    driver.get("https://qa.cmnetwork.co");
    driver.quit();