How to search node by exact text match using Xpath in webdriver

女生的网名这么多〃 提交于 2021-01-20 18:54:31

问题


I need a little help regarding searching an exact text using xpath in webDriver.

Suppose i have the html as follows..

<html><body>
  <table>
    <tr>
      <td><button>abcd</button></td>
      <td><button>abc</button></td>
    </tr>
  </table>
</body></html>

Now i want to click button "abc"

I used xpath as //button[contains(text(),'abc')] but it is always performing on button "abcd" as it also contain the text "abc". In this regards I need a predicate or some other procedure which can search exact text instead of containing text.

I also tried with //button[matches(text(),'abc')], //button[matches($string,'abc')], //button[Text='abc')], //button[.='abc')] and many more but none of these worked out to identify "abc" button.

I do not know if there is any problem regarding my xpath version as I'm not aware of the version. But I'm using java 1.6 JDK.

Though my exact scenario is not the example shown but similar logic needs to be applied.

Hence any help or suggestion would be highly appreciated.


回答1:


I would use next xpath //button[text()='abc']. You have mentioned text() function but I'm not sure syntax was correct. Also you tried to use contains() -- it searches partial text and WebDriver gets first element found. I your case it is <button>abcd</button> button




回答2:


To find the element 'abcd' you can simply use:

//button[contains(text(),'abcd')]

To find 'abc' use the normalize-space() function which will clean up your text for comparison purposes.

//button[normalize-space(text())='abc']



回答3:


//button[.="abc"]

The dot before the equality operator will do the text comparison. Another example is /PROJECT[.="MyProject"] from the xPath Java tutorial.




回答4:


Try with ends-with instead of contains. If the buttons dont have unique attributes, you can add the parent hierarchy as well. Like //table/tr/td[1].




回答5:


For exact search:

button[text()='abc']

For pattern matching search:

button[starts-with(.,'abc')]



回答6:


Using something like below worked perfectly fine for me.

//button[(contains(.,'abc')) and not(contains(.,'abcd'))]


来源:https://stackoverflow.com/questions/19721111/how-to-search-node-by-exact-text-match-using-xpath-in-webdriver

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!