Playwright Tip of the Week: Using internal:has-text in Locators
Playwright offers powerful locator strategies to find elements on a page. One such strategy is internal:has-text, which allows for precise text matching using regular expressions. This is particularly useful when dealing with dynamic elements where the text might have variations or when avoiding brittle XPath selectors.
Solution
You can use internal:has-text to locate elements based on their internal text content. It can be combined with other locators, such as CSS selectors, to further refine your selection. The syntax follows this pattern:
locator(<css-selector> >> internal:has-text=<regex>
)
This approach ensures that you only target elements that match both the CSS selector and the internal text pattern.
Example
Let’s consider a scenario where we want to locate a login button inside a specific section of a webpage. The button’s text may have leading or trailing spaces, or minor variations, so we use a regular expression to match it precisely.
Summary
• internal:has-text allows text matching using regular expressions within Playwright locators.
• It can be combined with CSS selectors to target elements more precisely.
• This method is particularly useful when text may have variations or whitespace differences.
• It improves test reliability by avoiding brittle selectors like XPath.
Try using internal:has-text in your Playwright tests for more flexible and robust locators! 🚀
Sapnesh Naik is the Head of QA at BlinqIO, where he leads quality assurance and client solution efforts. With deep expertise in test automation and software quality, Sapnesh focuses on solving real-world technical challenges and helping teams ship better software.
Want to contribute your own tips? Reach out to us at tips@playwright-user-event.org.