4

I am trying to find the list item based on the contents in the anchor.

I tried using the following xpath

//li/a[contains(., 'India')]

It is working for unique items, But here, it is matching more than one item.

I want to ignore the the other contents in anchor and only focus on the anchor text to identify the li. How can i achieve it?

<ul>
   <li style="display: list-item;"><a href="#"><img src="1" class="flag">&nbsp;Afghanistan</a></li>
   <li style="display: list-item;"><a href="#"><img src="2" class="flag">&nbsp;India</a></li>
   <li style="display: list-item;"><a href="#"><img src="3" class="flag">&nbsp;British Indian Ocean Territory</a></li>
</ul>

PS: Tried the following, it works. But later if the position of "&nbsp ;" changes, it's going to fail.

//li/a[ends-with(normalize-space(.),'India')]

1 Answer 1

2

Using normalize-space() was a good idea but it would not handle &nbsp; by definition. You can do two things:

  • translate a non-breaking space entity into a regular space
  • compare the full string value of a node with a desired string

Final XPath:

//li/a[normalize-space(translate(., '&#160;', ' ')) = 'India']

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.