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

Viewed 852

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}
2 Answers

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')]"
Related