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

I need a little help finding exact text using xpath in webDriver.

Suppose I have 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 the "abc" button

I used xpath as //button[contains(text(),'abc')] , but it always acts on the "abcd" button, since it also contains the text "abc". In this regard, I need a predicate or some other procedure that can search for exact text instead of text.

I also tried using //button[matches(text(),'abc')] , //button[matches($string,'abc')] , //button[Text='abc')] , //button[.='abc')] and many others, but none of them was designed to identify the "abc" button.

I do not know if there are any problems regarding my version of xpath, since I do not know about the version. But I am using java 1.6 JDK.

Although my exact scenario is not an example, similar logic should be applied.

Therefore, any help or suggestion would be greatly appreciated.

+13
source share
5 answers

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

+27
source
 //button[.="abc"] 

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

+2
source

Try with ends — instead of them. If buttons do not have unique attributes, you can also add a parent hierarchy. Like // table / tr / td [1].

0
source

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

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

To find 'abc', use the normalize-space () function, which will clear your text for comparison.

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

For an exact search:

 button[text()='abc'] 

To search by template:

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

Source: https://habr.com/ru/post/957161/


All Articles