To click a button with Playwright, use the click()
method on the element selected by the locator. For instance, to click a button with role "button", use the following code:
await page.getByRole('button').click();
Playwright also supports other types of clicks, such as double-clicks with dblclick()
and right-clicks with click({ button: 'right' })
. To perform a shift-click, use click({ modifiers: ['Shift'] })
. To hover over an element without clicking, use the hover()
method.
These methods ensure the element is in the DOM, displayed, not moving, and can receive pointer events. If any of these checks fail, Playwright retries the action.
In some cases, you might need to force the click by passing { force: true }
as an option to click()
. Use this only when necessary, as it bypasses some actionability checks.
Here's an example of clicking a button on a website:
import { test, expect } from '@playwright/test';
test('Click button on ray.run', async ({ page }) => {
await page.goto('https://ray.run/');
await page.getByRole('button').click();
// Add assertions or further interactions here
});
In this example, Playwright navigates to the website, clicks the button, and you can add further interactions or assertions as needed.
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].