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):

//*[text()='match']
//button[text()='Save']

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:

//*/text()[normalize-space(.)='match']/parent::*

Partly matching:

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

//*[contains(text(),'match')]

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:

//*[matches(text(),'(^|\W)match($|\W)','i')]

Search element with specific class

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

Get parent element

//*[contains(@class, 'Test')]/parent::*
or
//*[contains(@class, 'Test')]/..

Multiple conditions

NOTE: that you MUST use single quotes and the word ‘and’ MUST be lowercase.

//*[contains(@class, 'Test') and contains(text(), 'match this text')]

//button[@id='add-user' and contains(@class, 'active')]

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

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

Click Here to Leave a Comment Below

Leave a Reply: