Playwright Tutorial for Beginners 4 - Selectors and Locators

Kayode - Apr 16 '23 - - Dev Community

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();
});

Enter fullscreen mode Exit fullscreen mode

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>

  • wrap the text single or double quotes to make playwright match the exact text. For instance,

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

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

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');

Enter fullscreen mode Exit fullscreen mode

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

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .