Playwright Tutorial for Beginners 4 - Selectors and Locators

Playwright Tutorial for Beginners 4 - Selectors and Locators

Playwright locators and selectors

To interact with elements, you need to locate the element first. Selectors are used when locating an element. Then we can perform actions and write assertions on the elements by means of methods such click(), dbclick().

Ways to select locate an element in Playwright:

Text selectors

The selector locates element that contains specified text. e.g

test('Locate "Log in" button', async() => {
    await page.locate('text=Log in').click();

Text selector has a few variations:

  • text=Log in - default matching case is case-insensitive and searches for a sub string. For instance, text=Log matches <button>Log in</button>

      await page.locate('text=Log in').click();
  • wrap the text single or double quotes to make playwright match the exact text. For instance,

      await page.locator('text="Log"').click();

    the selector won’t locate <button>Log in</button> because the element does not contain a text node that is exactly Log. But if the element is <button> Log <span>in</span></button>, Playwright will select this element because the element both have a text node that is exactly Log and another nested span element node in it.

  • You can make use of a JavaScript-like regex wrapped in / symbol. For instance:

      await page.locator('text=/Log\s*in/i').click();
  • :has-text pseudo-class matches an element that contains specified text inside somewhere. It is used with other CSS specifiers because it will match all elements that contain the specified test. For instance

      // will match all element (both parent, child and <body>) that includes the element
      await page.locator(':has-text("Playwright")').click();
      // correct way, target element with text in classname "article"
      await page.locator('.article:has-text("Playwright")').click();

CSS selectors

CSS selector can be used in Playwright by :

  • CSS selector engine, e.g. page.locator(css='.button')
  • Using Playwright custom CSS locator with additional pseudo-classes like :visible, :text and many more

Query CSS selectors directly, for instance

await page.locator('.form > .button');

You can read more about selectors and locators in the official documentation.