Playwright provides several methods to interact with web elements. Let's explore some of them.
To click a button, first locate it using the getByRole
method. Then, call the click()
method on it. Here's how you do it:
await page.getByRole('button').click();
This simulates a human click, triggering any associated events.
If you need to type into an input field, use the locator.type()
method. This simulates a user typing on a real keyboard.
await page.locator('#area').type('Hello World!');
Playwright also lets you double-click, right-click, and hover over elements. Use the .dblclick()
, .click({button: 'right'})
, or .hover()
methods respectively.
await page.getByRole('button').dblclick();
await page.getByRole('button').click({button: 'right'});
await page.getByRole('button').hover();
Sometimes, hovering over an element overlays it with another one that intercepts clicks. In this case, you can force clicks by adding {force: true}
to your click options.
await page.getByRole('button').click({ force: true });
When writing tests, use web first assertions instead of manual ones. Web first assertions let Playwright wait until expected conditions are met before proceeding with test execution. This reduces the chances of flaky tests. For more on this, check out Mastering the Art of Detecting and Handling Flaky Tests in Playwright.
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].