Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 910
souvik Avatar asked Nov 01 '13 05:11

souvik


People also ask

How do I search for text in XPath?

So, inorder to find the Text all you need to do is: driver. findElement(By. xpath("//*[contains(text(),'the text you are searching for')]"));

What is text () in XPath?

XPath text() function is a built-in function of the Selenium web driver that locates items based on their text. It aids in the identification of certain text elements as well as the location of those components within a set of text nodes. The elements that need to be found should be in string format.

Which XPath function is used to extract all the elements which matches a particular text value?

We can extract all the elements that match the given text value using the XPath contains() function throughout the webpage.

How do I find dynamic XPath?

How to find XPath for dynamic elements in selenium? From the context (current) node, the XPath axes search different nodes in the XML document. For example, it is used to find the node closest to that tree.


2 Answers

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

like image 137
olyv Avatar answered Sep 20 '22 20:09

olyv


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'] 
like image 35
Priyanka Chaturvedi Avatar answered Sep 20 '22 20:09

Priyanka Chaturvedi