testerjoe2 testerjoe2 - 1 year ago 58
HTML Question

How do I select an element containing exactly the specified text using XPath?

Say we have an HTML table which basically looks like this:


I want to select the cells which contain only 8 and nothing else, that is, only 2nd cell of row2 and 3rd cell of row3.

This is what I tried:
. It gives me all cells which contain 8. So, I get unwanted values 28 and 18 as well.

How do I fix this?

EDIT: Here is a sample table if you want to try your xpath. Use the calendar on the left side-https://sfbay.craigslist.org/sfc/

Answer Source

Warning: Be careful of the contains() function.

It is a common mistake to use it to test if an element contains a value. What it really does is test if a string contains a substring. So, td[contains(.,'8')] takes the string value of td (.) and tests if it has any "8" substrings. This might be what you want, but often it is not.

This XPath,


will select all td elements whose space-normalized string value equals 8.


  • This will work even if the 8 is inside of another element such as a a, b, span, div, etc.
  • It will also work even if there's leading or trailing whitespace surrounding the 8.
  • This will not match td elements containing 80, 18, 1234567890, etc.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download