I have this html block:
<td><a href="#" class=""> <i class="far fa-times mr-1"></i>Cancel</a></td>
I wrote the following xpath to find this Cancel anchor, but this is not working. What am I doing wrong?
//a[contains(text(), 'Cancel')]
The following xpath works but i need to learn what am i doing wrong in the above one:
//i[@class='far fa-times mr-1']/..
2
Answers
Issue: The reason above XPath expression is not working is because, above XPath looks for an anchor (
<a>
) element containing the textCancel
. However, the<a>
element in your HTML snippet doesn’t directly contain the textCancel
. Instead, it contains an<i>
element and then the textCancel
.Solution: Change the XPath expression as below:
XPath explanation: The
.
represents the current node, socontains(., 'Cancel')
checks for the presence of "Cancel" text within the<a>
element and all of its descendants.The problem is that the first argument of contains should be a single string. And since
a
has 2 text-nodes, it fails. The first text-node is the white-space only node, the second is the one with Cancel inside.I see two alternatives:
//a[contains(., 'Cancel')]
The
.
will combine all descendent text-nodes into one string.//a[contains(text()[normalize-space()], 'Cancel')]
. The[normalize-space()]
-predicate will select only those text-nodes that have besides white-space actual character-data. Ans since that is only one, it will succeed.