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.
So, inorder to find the Text all you need to do is: driver. findElement(By. xpath("//*[contains(text(),'the text you are searching for')]"));
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.
We can extract all the elements that match the given text value using the XPath contains() function throughout the webpage.
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.
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
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With