How to find partial text using Playwright

Question:

I’m using Playwright to write automated tests.

My goal is to find an element by text contains and not by full match:

myElement = self.page.locator('text="Some Text 123"')

I wish to find only the elements with the text 123, how to do that?

Asked By: Tal Angel

||

Answers:

So for text selector, there are two behaviours, that you can look into:

  1. text=Log in – default matching is case-insensitive and searches for a substring.
  2. text="Log in" – text body can be escaped with single or double quotes to search for a text node with exact content.

So to search for a substring you can use the string without the double quotes:

myElement = self.page.locator('text=Some Text 123')
Answered By: Alapan Das

You can see from the documentation here that you can use pseudo-class of has-text

… the :has-text() pseudo-class

and maybe some some more advance matching selector with pseudo-class text-matches

the :text-matches() pseudo-class

but you need to remember that two ways is better if you combine the usage with some css selector.

Maybe you can add more details on where you want to search the string from is it literally in the entire document or not. (and I can update the answer with more detail code example according to your target)

Answered By: Fran N.J.