仅为 Chrome 获取 org.openqa.selenium.InvalidSelectorException

Getting org.openqa.selenium.InvalidSelectorException only for Chrome

我正在尝试使用查找元素在网页中查找按钮,该页面可以包含以下按钮 ID 之一。

driver.findElements(By.xpath("//*[contains(@id,'topBtn')]")) driver.findElements(By.xpath("//*[contains(@id,'WSMplasticTop')]")) driver.findElements(By.xpath("//*[contains(@id,'bottomApplyBtn')]"))

当我使用 Firefox 驱动程序时,上面的代码按预期工作,当我在 Chrome 驱动程序中 运行 时出现以下错误。

org.openqa.selenium.InvalidSelectorException: invalid selector: Unable to locate an element with the xpath expression //*[contains(@id='bottomApplyBtn')] because of the following error: SyntaxError: Failed to execute 'evaluate' on 'Document': The string '//*[contains(@id='bottomApplyBtn')]' is not a valid XPath expression.

只是想知道我有没有做错什么

尝试使用

'//*[contains(@id,'bottomApplyBtn')]'

而不是

'//*[contains(@id='bottomApplyBtn')]'

当您在 XPath 表达式中使用 contains 方法时,您基本上是在使用内置的 method 来查找元素。

此方法需要 2 个参数。

  1. 首先是您要搜索的标签。
  2. 第二个是您在上述标签中查找的实际文本值。

基本上你必须调用带有 2 个参数的方法,并且 2 个参数应该 comma 分开。

所以 //*[contains(@id='bottomApplyBtn')] 是错误的,您应该删除这个 = 符号。

//*[contains(@id, 'bottomApplyBtn')]
              |_______|____________________ Parameter 1
                      |__________________________________Parameter 2

希望对您有所帮助!