In Selenium WebDriver, how to use xpath for the below HTML using Link Text ("Add New Button")
<a href="SOME URL">
<span >
<i class=""/>
</span>Add New Button
</a>
I tried to inspect the element as below but all dint work
1) //a[text()='Add New Button']
2) //a[contains(text(),'Add New Button']
3) //a/span/i[text()='Add New Button']
4) //a/span/i[contains(text(),'Add New Button']
I know that 3 and 4 won't , but just tried it.
So for such a HTML DOM, How to find the link using the link text using xpath?
Best Answer
Some of the answers that were already given work, others don't. And I think the OP would benefit from more explanations.
Your original expression:
Does not work because the text node that contains "Add New Button" also has a newline character at the end.
The next one:
Does not work (leaving aside the missing parenthesis) because
text()
returns a sequence of nodes and a function likecontains()
will only evaluate the first node in the sequence. In this case, the first text node insidea
only contains whitespace and is not the one that contains "Add New Button".You can validate this claim with:
which will test whether the second text node of
a
contains "Add New Button" - and this expression will return thea
element. But the best solution in this case is:.
will evaluate to the so-called "string value" of an element, a concatenation of all its text nodes which will include "Add New Button".A solution with
normalize-space()
is also possible, but has nested predicates: