Finding a button on a webpage with Playwright can be done in several ways.
You can use chaining and filtering locators to narrow down the search to a specific part of the page. This allows you to filter locators by text or by another locator. Here's an example:
const button = page.locator('button').withText('Submit');
Avoid XPath or CSS selectors as they can change and lead to failing tests if your DOM structure changes.
Playwright's test generator can generate locators based on role, text, and test id locators. It improves the locator to make it resilient and uniquely identify the target element.
const button = page.locator('button').withRole('button').withText('Submit');
Playwright's new Locators API represents a view of elements on the page. Unlike ElementHandle which points directly at an element, Locator captures the logic of how to retrieve an element.
Playwright also offers experimental React and Vue selector engines that allow selecting elements by component name or property values.
When clicking on a button, you have several options such as specifying which mouse button to use, setting click count, adding delay between mousedown and mouseup, bypassing actionability checks with force option, specifying modifier keys during operation, and opting out waiting for navigations via noWaitAfter flag.
await button.click({ button: 'left', clickCount: 1, delay: 0 });
For more details, check out Understanding the Difference Between Locators and Selectors in @playwright/test.
If you still have questions, please ask a question and I will try to answer it.
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 [email protected].