DEV Community

Kayode
Kayode

Posted on • Originally published at blog.zt4ff.dev on

4 1 1 1 1

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

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.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more