How do you locate an element by text in Playwright?
Hi Shashank,
You can use page.locator('text="example text"')
to locate an element by its text content.
Check this blog to know more:
You can use XPath to locate an element by its text content. This is useful if you need more complex querying or if text content is dynamic. Here’s how you can do it:
const element = page.locator('//text()[contains(., "example text")]');
This XPath expression finds text nodes that contain the specified text. You can adjust the XPath to match the structure of your HTML if needed.
Using a CSS Selector with : has-text
If you prefer using CSS selectors, Playwright provides a :has-text pseudo-class that can be combined with other CSS selectors to locate elements by their text content:
const element = page.locator(‘css-selector:has-text(“example text”)’);
Replace css-selector with the actual CSS selector of the parent element or context, and “example text” with the text you’re looking for. This approach helps in narrowing down the search to specific sections of the page.