Selenium WebDriver XPath无效选择器错误。

3

我是一个新手,对于动态按钮使用selenium很困难。我正在编写selenium webdriver js脚本。

我在stackoverflow上搜索了一些类似的错误页面,但没有一个解决我的问题。

我想使用这个xpath。

/dom[@domain='localhost:3000']//div[#'search-results']//button[@innertext='Add Contact']

这是我的代码:

driver.wait(until.elementIsVisible(driver.findElement(By.xpath("/dom[@domain='localhost:3000']//div[#'search-results']//button[@innertext='Add Contact']"))))

并出现了以下错误

InvalidSelectorError: invalid selector: Unable to locate an element with the xpa
th expression /dom[@domain='localhost:3000']//div[#'search-results']//button[@in
nertext='Add Contact'] because of the following error:
SyntaxError: Failed to execute 'evaluate' on 'Document': The string '/dom[@domai
n='localhost:3000']//div[#'search-results']//button[@innertext='Add Contact']' i
s not a valid XPath expression.

以下是HTML代码

<button class="btn btn-success btn-sm pull-right" data-email-id="user3@netas.com.tr" data-user-id="user3@test1.netas.com.tr" data-name="user3 test">Add Contact</button>

你能帮我识别我的问题吗?

你的按钮是否包含在id为“search-results”的div中? - Rajeev Ranjan
2个回答

1

#search-results可以用于CSS选择器中的id属性,其值为'search-results'。在XPath中,您应该使用@id='search-results'

正如@JeffC所指出的那样,[@innertext='Add Contact']谓词应该替换为[.='Add Contact']


1
button[@innertext='Add Contact'] 也不是有效的... 应该是 button[.='Add Contact']。你可以把这个加到你的回答里。 - JeffC
是的,我错过了那个。 - Andersson

0

您使用的xpath需要进行一些修改。您可以跳过顶级标签,如dom及其属性,如domain,仍然构建一个唯一的cssSelectorxpath。此外,在构建cssSelector时使用#。话虽如此,我希望在我们的xpath中也不包括文本部分Add Contact

/dom[@domain='localhost:3000']//div[#'search-results']//button[@innertext='Add Contact']

根据您分享的 HTML,我们可以轻松构建一个独特的 cssSelectorxpath 来仅使用 class 属性来识别元素,如下所示:

  • cssSelector

    driver.findElement(By.cssSelector("button.btn.btn-success.btn-sm.pull-right"));
    
  • xpath

    driver.findElement(By.xpath("//button[@class='btn btn-success btn-sm pull-right']"));
    

谢谢。实际上,直接从Chrome中获取xPath解决了我的问题。之前我是通过第三方测试工具获取的。 - Rasim AVCI
没有答案,我只是写了谢谢因为不需要回答。 - Rasim AVCI

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接