How do I locate specific text on a webpage using Playwright?


Locating Text on a Webpage with Playwright

Playwright offers several ways to find specific text on a webpage. Let's dive in!

Using getByText

One method is getByText. This method locates elements containing a given text substring, exact string, or regular expression. It's handy when you want to find an element based on its visible text content.

Here's an example:

// DOM structure
// <div>Hello <span>world</span></div>
// <div>Hello</div>

// Locate the <span> element containing "world"

// Find the first <div> element containing "Hello world"
page.getByText('Hello world');

// Match the second <div> element containing "Hello"
page.getByText('Hello', { exact: true });

Chaining and Filtering Locators

Another option is to chain and filter locators. This narrows down the search to a specific part of the page.

// Click on an "Add to cart" button next to an item with text "Product 2"
await page
  .filter({ hasText: 'Product 2' })
  .getByRole('button', { name: 'Add to cart' })

Using Test ID Attributes

Playwright also provides methods for locating elements by their test id attribute, such as getByTestId and locator.filter(). By default, Playwright uses the data-testid attribute as its test id attribute, but this can be configured using selectors.setTestIdAttribute() if necessary.

Remember, it's best not to rely too heavily on CSS selectors or XPath expressions when locating elements in your tests. These selectors may change if your DOM structure changes. Instead, use user-facing attributes such as role or test id attributes whenever possible.

In conclusion, Playwright offers multiple ways to search for specific text on a page, including getByText(), chaining and filtering locators, and using user-facing attributes. Happy testing!


Thank you!
Was this helpful?
Still have questions?

If you still have questions, please ask a question and I will try to answer it.

Related Questions

AboutQuestionsDiscord ForumBrowser ExtensionTagsQA Jobs

Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email luc@ray.run.