XPATH: search element by text

When I write selenium/kantu end-to-end test I often need to use xpath to find certain elements.
And while it’s definitely not the fastest, searching elements by the text in it, is easy and fast to use. It’s also more descriptive to an untrained eye.

I often refer to this post on StackOverflow which has it written down quite neatly: https://stackoverflow.com/a/2994336

It basically comes down to this:

Literal match (= must match exactly and completely):


This matches: elements containing (just) the text ‘match’ and a button with (just) the text ‘Save’

Do you need to strip whitespace from texts in elements before you do the matching, then use this:


Partly matching:

If it’s ok to be not so strict, use this more loosely matching:


This matches texts like: ‘this match comes up‘ and ‘matches this’

If your text must match with words beginning with the text or lines starting or ending with that text, use this xpath 2.0 expression:


Search element with specific class

//*[contains(@class, 'Test')]

PRO-tip: use the inspector to test your xpath.

open the inspector and search (<C-f> or <Command+F>)