Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selenium FindElement and Chrome in Headless mode

After starting chromedriver.exe in headless mode following this advice and using just these arguments

 options.AddArgument("headless");
 options.AddArgument("window-size=1280,960");

The chromedriver opens invisibly. But Selenium's FindElement() command is not finding anything on the headless Chrome page. Instead it throws this exception:

An exception of type 'OpenQA.Selenium.NoSuchElementException' occurred in WebDriver.dll but was not handled in user code

Additional information: no such element: Unable to locate element:

Q1: Has anyone had success running Selenium commands in Chrome's headless mode?

Q2: Have you been able to use FindElement with a chromedriver running in headless mode? If yes, how did you do it?


After reading more, perhaps something along these lines may be necessary? Add this to the Chrome startup options and then maybe connect chromedriver to it?
"remote-debugging-port=9222"
But with that option the IWebDriver and chromedriver does not open.


Background info: to answer, why would you want to do this? The primary reason was for tests run as a part of CI. These are tests that run on a VM and may not support 1080p monitors. If we ran it in headless mode and set the resolution that way we could.

like image 220
jmbmage Avatar asked Nov 07 '22 18:11

jmbmage


1 Answers

Add below lines of code in your main class:

ChromeOptions options = new ChromeOptions(); 
options.setHeadless(true); 
options.addArguments("--window-size=1920,1080"); 
options.addArguments("--disable-gpu"); 
options.addArguments("--disable-extensions"); options.setExperimentalOption("useAutomationExtension", false); options.addArguments("--proxy-server='direct://'"); 
options.addArguments("--proxy-bypass-list=*"); 
options.addArguments("--start-maximized");
options.addArguments("--headless"); 
WebDriver driver = new ChromeDriver(options);
like image 113
Vasista TVN Avatar answered Nov 15 '22 10:11

Vasista TVN