selenium tests fail against headless chrome

dstaraster picture dstaraster · Nov 1, 2017 · Viewed 10.6k times · Source

I am trying to get my selenium test automation to run against headless chrome so that I can move it to TeamCity. I have not had any luck. When I run it, Chrome does appear to run headlessly (no browser pops up), but I get a NoSuchElementException. The automation works as expected when run non-headlessly. A snapshot taken just shows a white rectangle.

I have researched this issue extensively, but I have not been able to find a solution that works for me. It appears that the issue was reported in https://bugs.chromium.org/p/chromedriver/issues/detail?id=476, but it's marked fixed. I think the problem might be the wrong chromedriver, or maybe the wrong chromedriver/selenium combination, but I've tried all sorts of combinations and no love.

I am using:

  • selenium-java 3.6.0
  • chromedriver 2.33.506120
  • Windows 7 Enterprise Service Pack1, 64-bit

My code is:

...
ChromeOptions headlessOptions = new ChromeOptions();
headlessOptions.addArguments("--start-maximized");
headlessOptions.addArguments("--headless");
driver = new ChromeDriver(headlessOptions);
driver.get(url);
WebElement usernameTextfield = driver.findElement(By.cssSelector(".input.username"));
...

And the output is:

Starting ChromeDriver 2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f) on port 41402
Only local connections are allowed.
Nov 01, 2017 10:22:51 AM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: OSS

org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"css selector","selector":".input.username"}
  (Session info: headless chrome=62.0.3202.75)
  (Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 6.1.7601 SP1 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 0 milliseconds

This is preventing me from being able to include my test automation as part of our CI, so any help would be very much appreciated.

Answer

singidunumx picture singidunumx · Jan 4, 2018

I had the same issue, the local server was using selfsigned certificate, here is the combination that worked for me:

ChromeOptions options = new ChromeOptions();
options.addArguments("--headless");
options.addArguments("--disable-gpu");
options.addArguments("--no-sandbox");
options.addArguments("--allow-insecure-localhost");