Unable to maximize Safari browser on MAC with Selenium Webdriver - java

We are using Selenium with Java to automate our Web application. We have working code to run automated test scripts on Windows operating system for the three browsers (IE, Chrome, Firefox - Latest version).
We have got the requirement to run automated test scripts on MAC operating system - Safari browser.
Environment Details:
MAC OS version : macOS Sierra version 10.12.5
Safari browser version : 10.1.1(12603.2.4)
Selenium standalone server version : 3.4.0
Java version : 1.8.0_112
Connected MAC VM with VNC viewer (Sys admin team provided MAC VM for our testing).
While executing test scripts on MAC, below code is not maximizing Safari browser, which is working fine for other browsers(IE, Chrome and Firefox) on Windows. Due to this we are unable to locate some of the controls on application.
driver.manage().window().maximize();
We are not getting any exception, code is executing but not performing any action.
Please help to overcome Safari browser maximize issue on MAC.
Really I thought my issue got resolved with this solution, tried code to maximize Safari browser, but getting exception.
Code:
SafariOptions options = new SafariOptions();
options.setUseCleanSession(true);
driver = new SafariDriver(options);
JavascriptExecutor jse = (JavascriptExecutor)driver;
String screenWidth = jse.executeScript("return screen.availWidth").toString();
String screenHeight = jse.executeScript("return screen.availHeight").toString();
int intScreenWidth = Integer.parseInt(screenWidth);
int intScreenHeight = Integer.parseInt(screenHeight);
org.openqa.selenium.Dimension d = new org.openqa.selenium.Dimension(intScreenWidth, intScreenHeight);
driver.manage().window().setSize(d);
Exception:
Aug 07, 2017 3:11:53 PM org.openqa.selenium.remote.ProtocolHandshake
createSession INFO: Detected dialect: OSS Exception in thread "main"
org.openqa.selenium.NoSuchWindowException: A request to use a window
could not be satisfied because the window could not be found.
(WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 27 milliseconds Build info: version:
'3.4.0', revision: '5234b32', time: '2017-03-10 09:04:52 -0800' System
info: host: 'Mac.local', ip: 'fe80:0:0:0:4c6:11dc:3f91:11f8%en0',
os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.12.6',
java.version: '1.8.0_121' Driver info:
org.openqa.selenium.safari.SafariDriver Capabilities
[{applicationCacheEnabled=true, rotatable=false, databaseEnabled=true,
handlesAlerts=true, version=12603.3.8, cleanSession=true,
platform=MAC, nativeEvents=true, locationContextEnabled=false,
webStorageEnabled=true, browserName=safari, javascriptEnabled=true,
platformName=macOS, cssSelectorsEnabled=true}] Session ID:
BA265536-18D3-490E-B6DB-40D8BBF25937
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:216)
at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:168)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:638)
at org.openqa.selenium.remote.RemoteWebDriver$RemoteWebDriverOptions$RemoteWindow.setSize(RemoteWebDriver.java:860)
at Sample.Safari.main(Safari.java:20)

Safari browser maximize issue got resolved after upgrading Safari version to 11.0(12604.1.35)
And the working code is
driver.manage().window().maximize();

We have observe bug with new driver libraries. You can use slightly old jars which is able to handle new browsers versions.
You can also use other option for maximize the browser window.
Example :-
Add below option and pass it to driver :-
chromeOptions.addArguments("--start-maximized");
The full code will look like below :-
System.setProperty("webdriver.chrome.driver","D:\\Workspace\\JmeterWebdriverProject\\src\\lib\\chromedriver.exe");
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("--start-maximized");
driver = new ChromeDriver(chromeOptions);
OR
Toolkit toolkit = Toolkit.getDefaultToolkit();
int Width = (int) toolkit.getScreenSize().getWidth();
int Height = (int)toolkit.getScreenSize().getHeight();
//For Dimension class, Import following library "org.openqa.selenium.Dimension"
driver.manage().window().setSize(new Dimension(Width,Height));
driver.get("https://google.com");
OR
((IJavaScriptExecutor)driver).ExecuteScript("window.resizeTo(1024, 768);");
Try this on safari :-
JavascriptExecutor jse = (JavascriptExecutor)driver;
String screenWidth = jse.executeScript("return screen.availWidth").toString();
String screenHeight = jse.executeScript("return screen.availHeight").toString();
int intScreenWidth = Integer.parseInt(screenWidth);
int intScreenHeight = Integer.parseInt(screenHeight);
Dimension d = new Dimension(intScreenWidth, intScreenHeight);
driver.manage.window.setSize(d);
Below article will have these example in details :-
http://www.abodeqa.com/2015/01/20/maximize-window-using-selenium-webdriver-and-by-using-abstract-window-toolkit/
Hope it will help you :)

Related

org.openqa.selenium.WebDriverException: unknown error: cannot focus element using ChromeDriver Selenium and Java

I wish to load the 2048 game, and click on Down key.
I have tried the below code:
driver=new ChromeDriver();
driver.get("http://2048game.com");
String path="/html/body/div[2]/div[3]/div[3]/div[1]/div";
driver.findElement(By.xpath(path)).sendKeys(Keys.ARROW_DOWN);
path is the xpath of the left most upper tile.
Also tried .sendKeys(Keys.DOWN); and it did not help as well.
It successfully loads the page, but it does not press the DownKey?
My code in console complains with:
Exception in thread "main" org.openqa.selenium.WebDriverException: unknown error: cannot focus element
(Session info: chrome=69.0.3497.100)
(Driver info: chromedriver=2.30.477700 (0057494ad8732195794a7b32078424f92a5fce41),platform=Windows NT 10.0.17134 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 38 milliseconds
Build info: version: '3.4.0', revision: 'unknown', time: 'unknown'
System info: host: 'LAPTOP-BD6AOVKQ', ip: '192.168.1.208', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_171'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities [{applicationCacheEnabled=false, rotatable=false, mobileEmulationEnabled=false, networkConnectionEnabled=false, chrome={chromedriverVersion=2.30.477700 (0057494ad8732195794a7b32078424f92a5fce41), userDataDir=C:\Users\salman\AppData\Local\Temp\scoped_dir23108_15057}, takesHeapSnapshot=true, pageLoadStrategy=normal, databaseEnabled=false, handlesAlerts=true, hasTouchScreen=false, version=69.0.3497.100, platform=XP, browserConnectionEnabled=false, nativeEvents=true, acceptSslCerts=true, locationContextEnabled=true, webStorageEnabled=true, browserName=chrome, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true, unexpectedAlertBehaviour=}]
Session ID: 6be1718d9dbeddfa7508d895eb40a10c
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:215)
at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:167)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:671)
at org.openqa.selenium.remote.RemoteWebElement.execute(RemoteWebElement.java:272)
at org.openqa.selenium.remote.RemoteWebElement.sendKeys(RemoteWebElement.java:96)
at services.Hook.<init>(Hook.java:27)
at mains.Online2048.main(Online2048.java:9)
I have tried same code on firefox browser. Please have a look and it's working.
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.Platform;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
public class geckodriver {
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.gecko.driver", "C:\\Users\\XXXX\\Downloads\\geckodriver-v0.20.1-win64\\geckodriver.exe");
Thread.sleep(5000);
// DesiredCapabilities capabilities = DesiredCapabilities.firefox();
// capabilities.setCapability("marionette", true);
//
// WebDriver driver = new FirefoxDriver(capabilities);
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities = DesiredCapabilities.firefox();
capabilities.setBrowserName("firefox");
capabilities.setVersion("your firefox version");
capabilities.setPlatform(Platform.WINDOWS);
capabilities.setCapability("marionette", false);
WebDriver driver = new FirefoxDriver(capabilities);
// driver.get("http://www.google.com");
driver.get("http://2048game.com");
String path="/html/body/div[2]/div[3]/div[3]/div[1]/div";
driver.findElement(By.xpath(path)).sendKeys(Keys.ARROW_DOWN);
System.out.println("Done");
Thread.sleep(5000);
driver.quit();
}}
Based on error message an element you are trying to apply sendKeys to is not focused - thus ChromeDriver fails to interact with it.
In case you just want to press arrow down the following code should work (just changed the xPath from your example):
driver=new ChromeDriver();
driver.get("http://2048game.com");
String path="//*";
driver.findElement(By.xpath(path)).sendKeys(Keys.ARROW_DOWN);
This error message...
org.openqa.selenium.WebDriverException: unknown error: cannot focus element
...implies that the ChromeDriver was unable to focus on the desired WebElement.
Your main issue is the incompatibility between the version of the binaries you are using as follows:
You are using chromedriver=2.30
Release Notes of chromedriver=2.30 clearly mentions the following :
Supports Chrome v58-60
You are using chrome=69.0
Release Notes of chromedriver=2.42 clearly mentions the following :
Supports Chrome v68-70
Your Selenium Client version is 3.4.0 which is a bit older.
Your JDK version is 1.8.0_171 which is also a bit older.
So there is a clear mismatch between the JDK v8u171 , Selenium Client v3.4.0 , ChromeDriver v2.36 and the Chrome Browser v69.0
Solution
Upgrade JDK to recent levels JDK 8u181.
Upgrade Selenium to current levels Version 3.14.0.
Upgrade ChromeDriver to current ChromeDriver v2.42 level.
Keep Chrome version between Chrome v68-70 levels. (as per ChromeDriver v2.42 release notes)
Clean your Project Workspace through your IDE and Rebuild your project with required dependencies only.
If your base Web Client version is too old, then uninstall it through Revo Uninstaller and install a recent GA and released version of Web Client.
Execute your #Test.
Found solution using chromeDriver.
driver.get("http://2048game.com");
WebElement e1=driver.findElement(By.xpath("/html[1]/body[1]"));
e1.sendKeys(Keys.ARROW_DOWN);
System.out.println("Done");
Thread.sleep(15000);
driver.quit();
You need to set the focus on the element before sending keys to it.
In order to fix it, we can use Selenium Actions:
Actions assigner = new Actions(webdriver);
assigner.moveToElement(webelement);
assigner.click();
assigner.sendKeys("<your value>");
assigner.build().perform();

Unable to start Chrome browser with user profile in Selenium

I am trying to open a Chrome browser window with an existing user profile.
String dir= "/Users/labuser/Library/Application Support/Google/Chrome";
ChromeOptions options = new ChromeOptions();
options.addArguments("--user-data-dir="+dir);
driver = new ChromeDriver(options); // throws an exception!
I confirmed the user directory path by looking at chrome://version page. (screenshot below)
Due to some reason, this code throws an exception with very less information
org.openqa.selenium.WebDriverException: unknown error: Chrome failed to start: exited abnormally
(Driver info: chromedriver=2.33.506106 (8a06c39c4582fbfbab6966dbb1c38a9173bfb1a2),platform=Mac OS X 10.12.6 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 60.33 seconds
Build info: version: '2.53.0', revision: '35ae25b', time: '2016-03-15 17:00:58'
System info: host: 'arustagi-wx-3', ip: '10.41.25.35', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.12.6', java.version: '1.8.0_111'
Driver info: org.openqa.selenium.chrome.ChromeDriver
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:206)
at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:158)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:678)
at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:249)
at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:131)
at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:144)
at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:170)
at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:159)
at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:148)
Edit
I am using the following chrome browser, this falls in the supported range of browsers
Version 61.0.3163.100
You are using the latest version of the ChromeDriver
chromedriver=2.33.506106
with Selenium 2.53. You should use the latest release.
Anyway, what is your browser version? Here you can take a look which are the browsers version supported (based on your chromedriver).
EDIT
I tried with:
Selenium 3.5.3
ChromeDriver v2.33
Google Chrome Version 62.0.3202.62 (Official Build) (64-bit)
From chrome://version/, my profile path is
/Volumes/MacintoshSSD/Users/DurdenP/Library/Application Support/Google/Chrome/Default
Trying
String chromeDriver ="pathTo/ChromeDriver/chromedriver";
System.setProperty("webdriver.chrome.driver", chromeDriver);
ChromeOptions options = new ChromeOptions();
String dir= "/Volumes/MacintoshSSD/Users/DurdenP/Library/Application Support/Google/Chrome";
options.addArguments("user-data-dir="+dir);
ChromeDriver driver = new ChromeDriver(options);
it works.
Finally got this fixed. I was working on macOS and found out that i needed to quit the browser cleanly.
After closing the browser window, i had to right click on the icon in the dock and press quit. The selenium script would work perfectly fine after this.

How to run selenium tests on chrome if only binary file of chrome is placed in a server location in E drive

I have a situation in my project as below :
My code was executing as expected till the IT admin uninstalled chrome and FF from Jenkins server.
After raising a concern they placed a chrome binary in E drive .( E:\GC Local\GoogleChrome).But Chrome is not installed anywhere
I am facing issues to resolve this.
Do anyone guide here ?
Code I used :
if ("chrome".equals(browser))
{
System.setProperty("webdriver.chrome.driver",
System.getProperty("user.dir")
+ "\\src\\test\\resources\\drivers\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("--disable-extensions");
options.addArguments("--start-maximized");
driver = new ChromeDriver(options);
}
Will it work for you ?
ChromeOptions options = new ChromeOptions();
options.setBinary("E:\\GC Local\\GoogleChrome");
I understand that in homepath \app data chrome should be installed by default to run chrome tests. In my case , there is no chrome istalled in homepath-app but in E drive
When I used the below code :
ChromeOptions options = new ChromeOptions();
options.setBinary("E:\\GCLocal\\GoogleChrome\\GoogleChromePortable.exe");
// System.setProperty("webdriver.chrome.driver", "C:\\Selenium\\Browsers\\chromedriver.exe");
System.setProperty("webdriver.chrome.driver",
System.getProperty("user.dir")
+ "\\src\\test\\resources\\drivers\\chromedriver.exe");
driver = new ChromeDriver(options);
I am getting getting the following :
T E S T S
Running TestSuite
Browser :chrome
Starting ChromeDriver 2.29.461591 (62ebf098771772160f391d75e589dc567915b233) on port 45594
Only local connections are allowed.
Error in initializing the Test .Details :-
org.openqa.selenium.WebDriverException: unknown error: Chrome failed to start: exited normally
(Driver info: chromedriver=2.29.461591 (62ebf098771772160f391d75e589dc567915b233),platform=Windows NT 6.1.7601 SP1 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 62.74 seconds
Build info: version: '2.53.0', revision: '35ae25b1534ae328c771e0856c93e187490ca824', time: '2016-03-15 10:43:46'
System info: host: 'WHIS2002', ip: '10.192.129.112', os.name: 'Windows Server 2008 R2', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_77'
Driver info: org.openqa.selenium.chrome.ChromeDriver
./TestReport.html
The above approach is correct. My issue was that portable-chrome binary refused to open due to some issues in server .code was fine.
This happened because of portable chrome binary performance issues which I solved like this :
Google Chrome Portable may run slowly from some flash drives. You can speed this up by copying GoogleChromePortable.ini from the GoogleChromePortable\Other\Source directory to the GoogleChromePortable directory and editing it to set RunLocally=true. If you do so, be sure to allow Google Chrome Portable time to copy your profile back after shutting it down. Of course, there are privacy implications to copying your personal data locally to a PC not under your control.
Thanks

Selenium firefox - WebDriverException: Reached error page: about:certerror

Meta :-
Firefox v51.0.1 (32-bit)
Windows 10
Selenium 3.0.1
Geckodriver Win32 v0.13.0
Java v1.8.0_71
Steps to reproduce :-
WebDriver driver = new FirefoxDriver();
driver.get("untrusted/self-signed URL")
Stacktrace :-
org.openqa.selenium.WebDriverException: Reached error page: about:certerror?e=nssBadCert&u=xxxxxxxx&c=UTF-8&f=regular&d=xxxxxx%20uses%20an%20invalid%20security%20certificate.%0A%0AThe%20certificate%20is%20not%20trusted%20because%20it%20is%20self-signed.%0AThe%20certificate%20is%20not%20valid%20for%20the%20name%20xxxxxx%0A%0AError%20code%3A%20%3Ca%20id%3D%22errorCode%22%20title%3D%22SEC_ERROR_UNKNOWN_ISSUER%22%3ESEC_ERROR_UNKNOWN_ISSUER%3C/a%3E%0A
Build info: version: '3.0.1', revision: '1969d75', time: '2016-10-18 09:48:19 -0700'
System info: host: 'Saurabh-PC', ip: '192.168.3.8', os.name: 'Windows 10', os.arch: 'x86', os.version: '10.0', java.version: '1.8.0_71'
Driver info: org.openqa.selenium.firefox.FirefoxDriver
Screenshot :-
I have also tried using FirefoxProfile as :-
DesiredCapabilities dc = DesiredCapabilities.firefox();
dc.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
FirefoxProfile profile = new FirefoxProfile();
profile.setAcceptUntrustedCertificates(true);
dc.setCapability(FirefoxDriver.PROFILE, profile);
WebDriver driver = new FirefoxDriver(dc);
driver.get("untrusted/self-signed URL");
But issue is the same as above.
Reference Link which have tried :-
How to disable Firefox's untrusted connection warning using Selenium?
https://groups.google.com/forum/?fromgroups#!topic/webdriver/frWtNrEwNPk
Handling UntrustedSSLcertificates using WebDriver
According to this bug Support for untrusted/self-signed certificates has been added via bug 1103196 and will be available starting with Firefox 52.
But I could not find any solution for Firefox v51.0.1 (32-bit).
Is there any way to solve this issue using Firefox v51.0.1 (32-bit)?
As in this bug mentioned Support for untrusted/self-signed certificates will be available starting with Firefox 52, we need to wait until Firefox 52 is not released.
Solution :-
For now, as alternate solution we need to use existing Firefox profile where the certificate for untrusted/self-signed URL is already added into Firefox's exception list.
How to create custom Firefox profile for selenium?
Need to follow this link to create manually custom Firefox profile
Add manually certificate for untrusted/self-signed URL into Firefox's exception list
Launch Firefox using existing profile as :-
System.setProperty("webdriver.gecko.driver", "path/to/geckodriver")
ProfilesIni profile = new ProfilesIni();
FirefoxProfile myprofile = profile.getProfile("created Profile Name");
WebDriver driver = new FirefoxDriver(myprofile);
driver.get("untrusted/self-signed URL");

How to connect to Chromium Headless using Selenium

I would like to use chromium headless for automated testing using selenium. (https://chromium.googlesource.com/chromium/src/+/lkgr/headless/README.md)
I do have the headless version already running on 9222. So if i open http://10.252.100.33:9222/json/I do get
[ {
"description": "",
"devtoolsFrontendUrl": "/devtools/inspector.html?ws=127.0.0.1:9223/devtools/page/0261be06-1271-485b-bdff-48e443de7a91",
"id": "0261be06-1271-485b-bdff-48e443de7a91",
"title": "The Chromium Projects",
"type": "page",
"url": "https://www.chromium.org/",
"webSocketDebuggerUrl": "ws://127.0.0.1:9223/devtools/page/0261be06-1271-485b-bdff-48e443de7a91"
} ]
As a next step I'd like to connect selenium to the headless chromium. But when i try
final DesiredCapabilities caps = DesiredCapabilities.chrome();
final WebDriver driver = new RemoteWebDriver(new URL("http://localhost:9222/json"), caps);
driver.get("http://www.google.com");
I do get the following logout
Jän 24, 2017 7:14:45 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFORMATION: Attempting bi-dialect session, assuming Postel's Law holds true on the remote end
Jän 24, 2017 7:14:45 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFORMATION: Falling back to original OSS JSON Wire Protocol.
Jän 24, 2017 7:14:45 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFORMATION: Falling back to straight W3C remote end connection
org.openqa.selenium.SessionNotCreatedException: Unable to create new remote session. desired capabilities = Capabilities [{browserName=chrome, version=, platform=ANY}], required capabilities = Capabilities [{}]
Build info: version: '3.0.1', revision: '1969d75', time: '2016-10-18 09:49:13 -0700'
System info: host: 'Geralds-MacBook-Pro.local', ip: '192.168.0.249', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.12.2', java.version: '1.8.0_111'
Driver info: driver.version: RemoteWebDriver
Questions are:
Is the RemoteWebDriver the correct driver to connect to the headless
chromium?
I read about the DevTool protocol (https://docs.google.com/presentation/d/1gqK9F4lGAY3TZudAtdcxzMQNEE7PcuQrGu83No3l0lw/), but I'm not sure, how to create such a client using selenium.
Connecting the Chromium Headless using the Chrome DevTools works (https://developers.google.com/web/tools/chrome-devtools/remote-debugging/) besides some segmentation vaults ;-)
I think the readme is a little bit misleading. You don't have to start Chromium itself and you can use the RemoteWebDriver. Make sure that a chromedriver is installed (https://sites.google.com/a/chromium.org/chromedriver/home).
Start chromedriver (e.g. ./chromedriver or ./chromedriver --port=9515)
Then you have tell the chromedriver to use Chromium instead of Chrome
Add --headless as an additional argument
Code should look like this:
final ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.setBinary("/usr/bin/chromium-browser");
chromeOptions.addArguments("--headless");
desiredCapabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions);
WebDriver driver = new RemoteWebDriver(url, desiredCapabilities);
Worked for me on Ubuntu Linux.
Alternatively if your running it locally you can just do it like this. In scala.
val chromeOptions = new ChromeOptions
chromeOptions.addArguments("--headless")
new ChromeDriver(chromeOptions)
Use the following code:
ChromeOptions options = new ChromeOptions();
options.setHeadless(true); //Set Chrome option
driver = new ChromeDriver(options);
and you will get "Headless" Chrome!
Full code
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions; //import ChromeOptions
public class web_crawl {
private static WebDriver driver = null;
public static void main(String[] args) {
ChromeOptions options = new ChromeOptions();
options.setHeadless(true);
driver = new ChromeDriver(options);
driver.get("http://www.google.com"); //The website you want to connect to
}
if you are using selenium 3+ chrome driver , you can simply use chrome options and initiate driver. Check details in a project
Example Project on Chrome Headless running with different options
options.setHeadless(true)
System.setProperty("webdriver.chrome.driver", "Path of the chrome driver");
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("--headless");
chromeOptions.addArguments("--window-size=1920,1200");
webDriver = new ChromeDriver(chromeOptions);
The invisible browser window is only 800x600 in size. Therefore, you need to set the desired screen size with an additional argument
for me works above solution:
chromeOptions.setBinary("/usr/bin/chromium-browser");
but i had to add (becouse of devtools):
chromeOptions.addArguments("--remote-debugging-port=9222");
and disable firewall
Chrome 59 has the ability to create instance as headless . I have tried for Windows with new chrome driver 2.30 and it worked for me
https://www.automation99.com/2017/07/how-to-use-chrome-headless-using.html?m=1

Categories

Resources