给定的 xpath 表达式“//div[contains(@class='loader-overlay')]”对 Selenium 无效

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

从 2.53 版升级到 3.14 版后,Selenium 说

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

这段代码

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

产生此错误

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}

你需要更换

//div[contains(@class='loader-overlay')]

//div[contains(@class, 'loader-overlay')]

请注意,如果要检查 属性值是否恰好是 "value",则应使用 [@attr = "value"] 语法,但 contains 语法是 [contains(@attr, "value")]

这个错误信息...

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

...表示 xpath 表达式 无效。

解决方案

如果元素具有单个 class 属性 作为 loader-overlay 您需要将 xpath 更改为:

"//div[@class='loader-overlay']"

如果元素有多个 class 属性loader-overlay 是其中之一,您需要将 xpath 更改为:

"//div[contains(@class, 'loader-overlay')]"