selenium webdriver xpath InvalidSelectorError

时间:2017-10-15 15:58:39

标签: java selenium xpath webdriver

我是硒的新手,我真的很难在这里使用动态按钮。我正在写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>

你能帮我辨认一下我的问题吗?

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

您使用的xpath需要进行一些修改。您可以跳过顶级标记,例如 dom ,也可以跳过attributes domain ,并构建一个独特的cssSelectorxpath。构建#时会使用cssSelector以上的内容。话虽如此,我想避免在我们的Add Contact中包含 xpath 文字部分:

/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']"));
    
相关问题