I'm using id as identifier to find element, but exception stack trace is showing css selector [duplicate] - selenium

This question already has answers here:
Official locator strategies for the webdriver
(2 answers)
Closed 3 years ago.
I'm using Selenium Web driver with Java code. Whenever org.openqa.selenium.NoSuchElementException occurs, stack trace prints identifier method as css selector every time although I have used id to find web element.
I tried using xpath identifier and it prints perfect stack trace with correct identifier method. My sample code.
public void testMethod()
{
try
{
driver.findElement(By.id("test"));
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
Stack trace output:
org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"css selector","selector":"#test"}
(Session info: chrome=75.0.3770.100)
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '3.14.0', revision: 'aacccce0', time: '2018-08-02T20:19:58.91Z'
System info: host: 'DTB150', ip: '10.37.55.150', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_181'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities {acceptInsecureCerts: false, browserName: chrome, browserVersion: 75.0.3770.100, chrome: {chromedriverVersion: 75.0.3770.90 (a6dcaf7e3ec6f..., userDataDir: C:\Users\DEV~1.SOL\AppData\...}, goog:chromeOptions: {debuggerAddress: localhost:38152}, javascriptEnabled: true, networkConnectionEnabled: false, pageLoadStrategy: normal, platform: XP, platformName: XP, proxy: Proxy(), setWindowRect: true, strictFileInteractability: false, timeouts: {implicit: 0, pageLoad: 300000, script: 30000}, unhandledPromptBehavior: dismiss and notify}
Session ID: b6c8f6cd722e746281dd59657850e10f
*** Element info: {Using=id, value=test}
Check method in first line of exception. It says method: css selector although I'm using id to find element.
Is that some kind of error or I have misunderstood something or some problem with my code?

See the exception : Unable to locate element: {"method":"css selector","selector":"#test"}
in css selector # represent an id.
If id is test and you are using it like this :
driver.findElement(By.id("test"));
Exception should be related to id if not found.
But if you are using it like
driver.findElement(By.cssSelector("#test"));
You would get the same exception as mentioned above in OP.

Related

Selenium 4 and WebDriver implicitlyWait

In our Selenium projects we use Implicit waits and fluent waits. Basically, we use Implicit waits until we need something explicit. E.g., for normal findElements() calls we depend on the implicit wait, but when waiting for an element to disappear after clicking some button we use a fluent wait. (See code below).
The problem is that lately I'm seeing a number of timeouts when calling implicityWait(n). This seems new. Maybe even in Selenium 4.3. Cannot say for sure, but it has certainly become bothersome. To be clear, "occasionally" means a couple of times over a couple of hundred tests (each calling implicitlyWait dozens of times).
public void waitUntilElementDisappear(By locator, int waitTime) throws Exception, TimeoutException {
Logger.log(String.format("Waiting [%ds] for [%s] to disappear", waitTime, locator));
try {
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(0));
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(waitTime));
wait.until(ExpectedConditions.invisibilityOfElementLocated(locator));
} catch (TimeoutException e) {
Logger.log("Caught timeout exception");
throw e;
} catch (Exception e) {
Logger.log(String.format("Caught exception message:[%s]", e.getMessage()));
throw e;
} finally {
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(DEFAULT_WAIT));
}
}
The issue occurs only in the finally block. (DEFAULT_WAIT is usually 180).
Any suggestions?
The exception:
org.openqa.selenium.TimeoutException: java.util.concurrent.TimeoutException
Build info: version: '4.3.0', revision: 'a4995e2c09*'
System info: host: 'DESKTOP-8Q1PEBT', ip: '172.32.6.43', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '11.0.15'
Driver info: org.openqa.selenium.remote.RemoteWebDriver
Command: [e8d45a02973053acad1a896d2ed471e6, setTimeout {implicit=0}]
Capabilities {acceptInsecureCerts: false, browserName: chrome, browserVersion: 103.0.5060.134, chrome: {chromedriverVersion: 103.0.5060.134 (8ec6fce403b..., userDataDir: C:\Users\jenkins\AppData\Lo...}, goog:chromeOptions: {debuggerAddress: localhost:59791}, networkConnectionEnabled: false, pageLoadStrategy: normal, platformName: WINDOWS, proxy: Proxy(), se:cdp: ws://172.32.6.43:4444/sessi..., se:cdpVersion: 103.0.5060.134, setWindowRect: true, strictFileInteractability: false, timeouts: {implicit: 0, pageLoad: 300000, script: 30000}, unhandledPromptBehavior: dismiss and notify, webauthn:extension:credBlob: true, webauthn:extension:largeBlob: true, webauthn:virtualAuthenticators: true}
Session ID: e8d45a02973053acad1a896d2ed471e6
at org.openqa.selenium.remote.http.netty.NettyHttpHandler.makeCall(NettyHttpHandler.java:65)
I still see following in Chrome 104
10:48:48 Build info: version: '4.3.0', revision: 'a4995e2c09*'
10:48:48 System info: host: 'DESKTOP-8Q1PEBT', ip: '172.32.6.43', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '11.0.15'
10:48:48 Driver info: org.openqa.selenium.remote.RemoteWebDriver
10:48:48 Command: [f97c4a4cd7a0d468391badd20e23fe8f, setTimeout {implicit=240000}]
10:48:48 Capabilities {acceptInsecureCerts: false, browserName: chrome, browserVersion: 104.0.5112.81, chrome: {chromedriverVersion: 104.0.5112.79 (3cf3e8c8a07d..., userDataDir: C:\Users\jenkins\AppData\Lo...}, goog:chromeOptions: {debuggerAddress: localhost:56549}, networkConnectionEnabled: false, pageLoadStrategy: normal, platformName: WINDOWS, proxy: Proxy(), se:cdp: ws://172.32.6.43:4444/sessi..., se:cdpVersion: 104.0.5112.81, setWindowRect: true, strictFileInteractability: false, timeouts: {implicit: 0, pageLoad: 300000, script: 30000}, unhandledPromptBehavior: dismiss and notify, webauthn:extension:credBlob: true, webauthn:extension:largeBlob: true, webauthn:virtualAuthenticators: true}
10:48:48 Session ID: f97c4a4cd7a0d468391badd20e23fe8f]
10:48:48 org.openqa.selenium.TimeoutException: java.util.concurrent.TimeoutException
Still not fixed in ChromeDriver. :(
I decided the only solution was to catch the exception and try again as
#pcalkins suggested.
public void setImplicitWait(int maxWaitTime) {
try {
this.driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(maxWaitTime));
} catch (TimeoutException e) {
this.driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(maxWaitTime));
}
}
Of course there could be a counter and a max retry, but so far I've found just 1 retry and it never fails.
I ended up wrapping a whole bunch of basic methods (e.g., findElement) in the same manner.
I know it is crude but so far seems to be my solution.
To bell the cat as per the Selenium Documentation:
Warning: Do not mix implicit and explicit waits. Doing so can cause unpredictable wait times. For example, setting an implicit wait of 10 seconds and an explicit wait of 15 seconds could cause a timeout to occur after 20 seconds.
Solution
To simulate the expectation for checking for the element to be invisible you can use either of the following approaches:
Using invisibilityOf(WebElement element):
new WebDriverWait(driver, Duration.ofSeconds(waitTime)).until(ExpectedConditions.invisibilityOf(driver.findElement(By.cssSelector("ElementCss"))));
Using invisibilityOfElementLocated(By locator):
new WebDriverWait(driver, Duration.ofSeconds(waitTime)).until(ExpectedConditions.invisibilityOfElementLocated(By.cssSelector("ElementCss")));

Unhandled inspector error - {"code":-32000,"message":"Object reference chain is too long"} in selenoid

Selenoid version - 1.10.0
Chrome version - 85.0
Docker image - selenoid/vnc_chrome:81.0
Exception -
org.openqa.selenium.WebDriverException: unknown error: unhandled inspector error: {"code":-32000,"message":"Object reference chain is too long"}
(Session info: chrome=80.0.3987.87)
Build info: version: '3.14.0', revision: 'aacccce0', time: '2018-08-02T20:19:58.91Z'
System info: host: 'mani-zt254', ip: 'fe80:0:0:0:4b9:53da:b2d:19d3%en0', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.14.6', java.version: '1.8.0_191'
Driver info: org.openqa.selenium.remote.RemoteWebDriver
Capabilities {acceptInsecureCerts: false, browserName: chrome, browserVersion: 80.0.3987.87, chrome: {chromedriverVersion: 80.0.3987.16 (320f6526c1632..., userDataDir: /tmp/.com.google.Chrome.g10u57}, goog:chromeOptions: {debuggerAddress: localhost:45089}, javascriptEnabled: true, networkConnectionEnabled: false, pageLoadStrategy: normal, platform: LINUX, platformName: LINUX, proxy: Proxy(), setWindowRect: true, strictFileInteractability: false, timeouts: {implicit: 0, pageLoad: 300000, script: 30000}, unhandledPromptBehavior: accept}
Session ID: 53b76f85512a10c9c08655240eef4042
Scenario
The above exception occurs while finding an element/performing any operation using jquery 1.x versions
So I inject the latest jQuery 3.5.0 able to perform the actions using jquery but some pages some jquery methods conflict occur due to this some errors occur in browser console click is not working in some elements, the above problems are there chrome 80.0 and above versions, now I'm using chrome 85.0.
Probably instead of calling:
evaluate_script
You should call:
execute_script
To elaborate. There is not so much information in the question itself, but in the feature test, if you are calling a script to be executred, you should call it with execute_script and not with evaluate_script
But there is not so much information in the question form a year or so, so just giving a wild quess.

Not navigating pagination3 and getting stale element exception

I need to navigate pages and check services on each page down or up, but while navigating page 3 is showing error message as stale element exception.
I have tried with this code but it's not working fine , someone please help me on this.
public class TC_2377154_12236_Verify_SRS_ServerStatus_LinuxServer {
public static void TC_2377154_12236() {
try {
Assert.done("Start -> TC_2377154_12236");
//BaseSetUp.openBrowser();
WebDriver driver = FrameworkDriver.driver;
driver.get("https://webtech.humana.com/nes/servicesview.aspx");
Assert.assertTrue(driver.findElement(By.xpath("//input[#id='tbLBVServerName']")).isDisplayed(), "LBV Server name is displayed");
driver.findElement(By.xpath("//input[#id='tbLBVServerName']")).sendKeys("SRS");
Assert.assertTrue(driver.findElement(By.xpath("//input[#id='btnFilter']")).isDisplayed(),"Filter button is displayed");
driver.findElement(By.xpath("//input[#id='btnFilter']")).click();
Assert.assertTrue(driver.findElement(By.xpath("//table[#id='dgServices']")).isDisplayed(),"Services name table is Displayed");
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until( ExpectedConditions.presenceOfElementLocated(
By.xpath("//a[#style='color:Black;']")));
List<WebElement> pagination = driver.findElements(By.xpath("//a[#style='color:Black;']"));
int s = pagination.size()/2;
System.out.println(s +"Pagination list");
for(int i=0;i<=s;i++){
List<WebElement> ls = driver
.findElements(By
.xpath("//font[#color='red']"));
System.out.println(ls.size()+"list of Down services size");
if (ls.size() > 1)
Assert.fail("All service states are expected Up and Running but there are "+(ls.size()+" servers are down"));
else if (ls.size() == 0)
Assert.fail("****Some technical issue or No Server is up or running****");
else if (ls.size() == 1)
Assert.pass("~~All Servers are Up and running~~");
Thread.sleep(5000);
// ls.get(i).click();
// Thread.sleep(5000);
System.out.println( pagination.get(i));
//driver.findElement(By.xpath("//a[#style='color:Black;']")).click();
pagination.get(i).click();
Thread.sleep(5000);
}
Assert.done("End -> TC_2377154_12236");
} catch (Exception e) {
Assert.error(e, "Error -> TC_2377154_12236");
}
}
}
I expected output as it should click on each and every page , but getting below error
TC_2377154_12236_Verify_SRS_ServerStatus_LinuxServer-TC_2377154_12236 : PASS - Filter button is displayed
TC_2377154_12236_Verify_SRS_ServerStatus_LinuxServer-TC_2377154_12236 : PASS - Services name table is Displayed
7Pagination list
5list of Down services size
TC_2377154_12236_Verify_SRS_ServerStatus_LinuxServer-TC_2377154_12236 : FAIL - All service states are expected Up and Running but there are 5 servers are down
[[ChromeDriver: chrome on XP (4f932cb86e8057b5ecda92c582500243)] -> xpath: //a[#style='color:Black;']]
TC_2377154_12236_Verify_SRS_ServerStatus_LinuxServer-TC_2377154_12236 : FAIL - Error -> TC_2377154_12236. Error:stale element reference: element is not attached to the page document
(Session info: chrome=77.0.3865.90)
(Driver info: chromedriver=2.37.544315 (730aa6a5fdba159ac9f4c1e8cbc59bf1b5ce12b7),platform=Windows NT 10.0.16299 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 0 milliseconds
For documentation on this error, please visit: https://www.seleniumhq.org/exceptions/stale_element_reference.html
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:25:48'
System info: host: 'WKR90LDWJ0', ip: '10.94.27.177', os.name: 'Windows 10', os.arch: 'x86', os.version: '10.0', java.version: '1.8.0_192'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities {acceptInsecureCerts: false, acceptSslCerts: false, applicationCacheEnabled: false, browserConnectionEnabled: false, browserName: chrome, chrome: {chromedriverVersion: 2.37.544315 (730aa6a5fdba15..., userDataDir: C:\Users\VAM1449\AppData\Lo...}, cssSelectorsEnabled: true, databaseEnabled: false, handlesAlerts: true, hasTouchScreen: false, javascriptEnabled: true, locationContextEnabled: true, mobileEmulationEnabled: false, nativeEvents: true, networkConnectionEnabled: false, pageLoadStrategy: normal, platform: XP, platformName: XP, rotatable: false, setWindowRect: true, takesHeapSnapshot: true, takesScreenshot: true, unexpectedAlertBehaviour: , unhandledPromptBehavior: , version: 77.0.3865.90, webStorageEnabled: true}
Session ID: 4f932cb86e8057b5ecda92c582500243 Stack Trace: [Ljava.lang.StackTraceElement;#18d3f76
FAIL Error:stale element reference: element is not attached to the page document
(Session info: chrome=77.0.3865.90)
(Driver info: chromedriver=2.37.544315 (730aa6a5fdba159ac9f4c1e8cbc59bf1b5ce12b7),platform=Windows NT 10.0.16299 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 0 milliseconds
For documentation on this error, please visit: https://www.seleniumhq.org/exceptions/stale_element_reference.html
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:25:48'
System info: host: 'WKR90LDWJ0', ip: '10.94.27.177', os.name: 'Windows 10', os.arch: 'x86', os.version: '10.0', java.version: '1.8.0_192'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities {acceptInsecureCerts: false, acceptSslCerts: false, applicationCacheEnabled: false, browserConnectionEnabled: false, browserName: chrome, chrome: {chromedriverVersion: 2.37.544315 (730aa6a5fdba15..., userDataDir: C:\Users\VAM1449\AppData\Lo...}, cssSelectorsEnabled: true, databaseEnabled: false, handlesAlerts: true, hasTouchScreen: false, javascriptEnabled: true, locationContextEnabled: true, mobileEmulationEnabled: false, nativeEvents: true, networkConnectionEnabled: false, pageLoadStrategy: normal, platform: XP, platformName: XP, rotatable: false, setWindowRect: true, takesHeapSnapshot: true, takesScreenshot: true, unexpectedAlertBehaviour: , unhandledPromptBehavior: , version: 77.0.3865.90, webStorageEnabled: true}
Session ID: 4f932cb86e8057b5ecda92c582500243 Stack Trace:
org.openqa.selenium.StaleElementReferenceException: stale element reference: element is not attached to the page document
(Session info: chrome=77.0.3865.90)
(Driver info: chromedriver=2.37.544315 (730aa6a5fdba159ac9f4c1e8cbc59bf1b5ce12b7),platform=Windows NT 10.0.16299 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 0 milliseconds
For documentation on this error, please visit: https://www.seleniumhq.org/exceptions/stale_element_reference.html
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:25:48'
System info: host: 'WKR90LDWJ0', ip: '10.94.27.177', os.name: 'Windows 10', os.arch: 'x86', os.version: '10.0', java.version: '1.8.0_192'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities {acceptInsecureCerts: false, acceptSslCerts: false, applicationCacheEnabled: false, browserConnectionEnabled: false, browserName: chrome, chrome: {chromedriverVersion: 2.37.544315 (730aa6a5fdba15..., userDataDir: C:\Users\VAM1449\AppData\Lo...}, cssSelectorsEnabled: true, databaseEnabled: false, handlesAlerts: true, hasTouchScreen: false, javascriptEnabled: true, locationContextEnabled: true, mobileEmulationEnabled: false, nativeEvents: true, networkConnectionEnabled: false, pageLoadStrategy: normal, platform: XP, platformName: XP, rotatable: false, setWindowRect: true, takesHeapSnapshot: true, takesScreenshot: true, unexpectedAlertBehaviour: , unhandledPromptBehavior: , version: 77.0.3865.90, webStorageEnabled: true}
Session ID: 4f932cb86e8057b5ecda92c582500243
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:214)
at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:166)
at org.openqa.selenium.remote.http.JsonHttpResponseCodec.reconstructValue(JsonHttpResponseCodec.java:40)
at org.openqa.selenium.remote.http.AbstractHttpResponseCodec.decode(AbstractHttpResponseCodec.java:80)
at org.openqa.selenium.remote.http.AbstractHttpResponseCodec.decode(AbstractHttpResponseCodec.java:44)
at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:158)
at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:83)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:552)
at org.openqa.selenium.remote.RemoteWebElement.execute(RemoteWebElement.java:285)
at org.openqa.selenium.remote.RemoteWebElement.click(RemoteWebElement.java:84)
at com.humana.hss.scripts.TC_2377154_12236_Verify_SRS_ServerStatus_LinuxServer.TC_2377154_12236(TC_2377154_12236_Verify_SRS_ServerStatus_LinuxServer.java:54)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.dell.acoe.framework.run.ExecutionThread.run(ExecutionThread.java:33)
Executing method [TC_2377154_12236]... completed
There is an issue while updating the script status to excel report. Please check file:null
Total:2
Passed:1 50%
Custom Report Generator is configured as:
TC_2377154_12236_Verify_SRS_ServerStatus_LinuxServer-TC_2377154_12236 : DONE - Custom Report Generator is configured as:
is not a valid CustomReportGenerator, it needs package.Class.method format and with two String args
TC_2377154_12236_Verify_SRS_ServerStatus_LinuxServer-TC_2377154_12236 : DONE - is not a valid CustomReportGenerator, it needs package.Class.method format and with two String args
Don't retrieve multiple elements out of For Loop.
You should find each element in For Loop again.
WebElement pag = diver.findElement(By.xpath("(//a[#style='color:Black;'])["+(i+1)+"]"));
Xpath example (you can search in web console):
(//a[#style='color:Black;'])[1]
List<WebElement> pagination = driver.findElements(By.xpath("//a[#style='color:Black;']"));
int s = pagination.size()/2;
System.out.println(s +"Pagination list");
for(int i=0;i<=s;i++){
// Add this line
WebElement pag = diver.findElement(By.xpath("(//a[#style='color:Black;'])["+(i+1)+"]"));
List<WebElement> ls = driver.findElements(By.xpath("//font[#color='red']"));
System.out.println(ls.size()+"list of Down services size");
if (ls.size() > 1)
Assert.fail("All service states are expected Up and Running but there are "+(ls.size()+" servers are down"));
else if (ls.size() == 0)
Assert.fail("****Some technical issue or No Server is up or running****");
else if (ls.size() == 1)
Assert.pass("~~All Servers are Up and running~~");
Thread.sleep(5000);
// ls.get(i).click();
// Thread.sleep(5000);
System.out.println( pagination.get(i));
//driver.findElement(By.xpath("//a[#style='color:Black;']")).click();
// Modify this line
pag.click();
Thread.sleep(5000);
}

"TypeError: rootNode is null" happens when taking screenshots using Selenium framework

Why this error TypeError: rootNode is null happens when taking screenshots? Is there a problem in HTML DOM structure which the developer should fix or is it a problem with Selenium version?
This error is happening when taking screenshot:
org.openqa.selenium.WebDriverException: TypeError: rootNode is null
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:17:03'
System info: host: 'linuxhost', ip: 'x.x.x.x', os.name: 'Linux', os.arch: 'amd64', os.version: '2.6.32-754.17.1.el6.x86_64', java.version: '1.8.0_202'
Driver info: org.openqa.selenium.firefox.FirefoxDriver
Capabilities {acceptInsecureCerts: true, browserName: firefox, browserVersion: 60.8.0, javascriptEnabled: true, moz:accessibilityChecks: false, moz:headless: false, moz:processID: 6651, moz:profile: /tmp/rust_mozprofile.LlBKoU..., moz:useNonSpecCompliantPointerOrigin: false, moz:webdriverClick: true, pageLoadStrategy: normal, platform: LINUX, platformName: LINUX, platformVersion: 2.6.32-754.17.1.el6.x86_64, rotatable: false, timeouts: {implicit: 0, pageLoad: 300000, script: 30000}}
Session ID: 1afd06ed-4939-42c9-9d1d-51fa113dfe97
at org.openqa.selenium.remote.http.W3CHttpResponseCodec.createException(W3CHttpResponseCodec.java:187)
at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:122)
at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:49)
at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:158)
at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:83)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:552)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:609)
at org.openqa.selenium.remote.RemoteWebDriver.getScreenshotAs(RemoteWebDriver.java:295)
dependency version:
Firefox: Mozilla Firefox 60.8.0
geckodriver: 0.23.0
selenium: 3.141.59
geb-spock:3.0.1
I just tried and it worked for me.
Firefox : 69.0 (64-bit)
Gecko Driver: v0.25.0
Webdriver: 3.141.59
FirefoxDriver fdriver;
System.setProperty("webdriver.gecko.driver", "/path/geckodriver");
DesiredCapabilities capabilities = DesiredCapabilities.firefox();
capabilities.setCapability("marionette", true);
FirefoxOptions foptions = new FirefoxOptions();
foptions.merge(capabilities);
fdriver = new FirefoxDriver(foptions);
fdriver.get("http://demo.guru99.com/selenium/guru99home/");
File src = ((TakesScreenshot) fdriver).getScreenshotAs(OutputType.FILE);
try {
// now copy the screenshot to desired location using copyFile //method
FileUtils.copyFile(src, new File("path/fchart.png"));
fdriver.quit();
}
catch (IOException e) {
System.out.println(e.getMessage());
}
I found out why "TypeError: rootNode is null" error is happening.
This error happens if test is trying to taking screenshot before even the html page source is completely downloaded.
Adding a dynamic wait to wait for page to load completely did fixed this issue.
waitFor {
((JavascriptExecutor)driver).executeScript("return document.readyState").equals("complete")
}
takeScreenshot()

Given xpath expression "//div[contains(#class='loader-overlay')]" is invalid with Selenium

After upgrading from version 2.53 to version 3.14 Selenium says
Given xpath expression "//div[contains(#class='loader-overlay')]" is invalid
This code
System.setProperty("webdriver.gecko.driver", "/path/to/geckodriver/v0.23.0");
FirefoxOptions options = new FirefoxOptions();
//...
driver = new FirefoxDriver(options);
WebElement loaderElement = driver.findElement(By.xpath("//div[contains(#class='loader-overlay')]"));
produces this error
org.openqa.selenium.InvalidSelectorException: Given xpath expression "//div[contains(#class='loader-overlay')]" is invalid: [Exception... "<no message>" nsresult: "0x8060000d (<unknown>)" location: "JS frame :: chrome://marionette/content/element.js :: element.findByXPath :: line 401" data: no]
For documentation on this error, please visit: http://seleniumhq.org/exceptions/invalid_selector_exception.html
Build info: version: '3.14.0', revision: 'aacccce0', time: '2018-08-02T20:19:58.91Z'
System info: host: 'xxx', ip: '10.233.112.79', os.name: 'Linux', os.arch: 'amd64', os.version: '4.4.0-116-generic', java.version: '1.8.0_181'
Driver info: org.openqa.selenium.firefox.FirefoxDriver
Capabilities {acceptInsecureCerts: true, browserName: firefox, browserVersion: 64.0, javascriptEnabled: true, moz:accessibilityChecks: false, moz:geckodriverVersion: 0.23.0, moz:headless: false, moz:processID: 2736, moz:profile: /tmp/rust_mozprofile.OP8KKQ..., moz:shutdownTimeout: 60000, moz:useNonSpecCompliantPointerOrigin: false, moz:webdriverClick: true, pageLoadStrategy: normal, platform: LINUX, platformName: LINUX, platformVersion: 4.4.0-116-generic, rotatable: false, setWindowRect: true, timeouts: {implicit: 0, pageLoad: 300000, script: 30000}, unhandledPromptBehavior: dismiss and notify}
You need to replace
//div[contains(#class='loader-overlay')]
with
//div[contains(#class, 'loader-overlay')]
Note that you should use [#attr = "value"] syntax if you want to check if attribute value is exactly the "value", but contains syntax is [contains(#attr, "value")]
This error message...
org.openqa.selenium.InvalidSelectorException: Given xpath expression "//div[contains(#class='loader-overlay')]" is invalid: [Exception... "<no message>" nsresult: "0x8060000d (<unknown>)" location: "JS frame :: chrome://marionette/content/element.js :: element.findByXPath :: line 401" data: no]
For documentation on this error, please visit: http://seleniumhq.org/exceptions/invalid_selector_exception.html
...implies that that the xpath expression was not a valid one.
Solution
If the element is having a single class attribute as loader-overlay you need to change the xpath as:
"//div[#class='loader-overlay']"
If the element is having multiple class attributes and loader-overlay is one among them you need to change the xpath as:
"//div[contains(#class, 'loader-overlay')]"