🚀 NEW: Pop-up Windows Recording - See how to test seamlessly OAuth integrations

Close announcement
Back to blog

Playwright Cheat Sheet

playwright cheat sheet

Playwright is an open-source automation library for web testing and automation. It allows developers to write scripts that can control a web browser and perform actions just like a human would, such as clicking on elements, typing text, navigating through pages, and capturing screenshots.

Playwright supports multiple browsers, including Chrome, Firefox, and WebKit, which allows for cross-browser testing. It provides a powerful API to automate web interactions and is capable of running tests in headless mode (without a browser UI) for faster execution.

Playwright cheat sheet

Playwright is often used for end-to-end testing, ensuring that web applications work as expected. It's a project maintained by Microsoft and is part of their modern testing toolset that also includes tools like Selenium and Cypress.

Let's dive into a comprehensive cheat sheet which can help you with mastering Playwright.

Why Use Playwright?


It enables interaction with elements of a web page, handling tasks from inputting text to asserting the visibility of a key element. Its robust API supports automation scenarios such as navigating browsers, managing cookies, and capturing dialog boxes.

Playwright tests can emulate complex user interactions with a web's structure, including selecting items from a list, clicking on labels, or handling CSS selectors.

Compared to tools like Cypress, Playwright offers cross-browser testing capabilities and the flexibility to write tests in multiple programming languages. Developers can write Playwright code to automate and interact with web elements, ensuring their applications work as intended in different environments.

Check out also our other Cheat Sheets:


In Playwright, a Browser represents an instance of a web browser. It's not just limited to a single tab or window; rather, it's the actual program itself, like an instance of Chrome or Firefox. When you start a browser through Playwright, you're effectively opening the application which can then contain multiple web pages and contexts.


A BrowserContext is an independent incarnation of a browser environment within Playwright. It can be thought of as an incognito session where no state is shared with other browser contexts.

This isolation is particularly useful for simulating multiple sessions or users in testing scenarios. Each context can have its own cookies, local storage, and session information, and you can have multiple contexts within the same browser instance.


A Page in Playwright is akin to a single tab or window in a web browser. It provides methods to interact with and control a single web page. Actions such as navigating to URLs, interacting with page content, and evaluating JavaScript within the context of the web page are done at this level. Pages live within a browser context, and you can have multiple pages within a single context.

Understanding Selectors and Elements

Selectors are the means by which Playwright identifies elements on a web page to interact with. They can be CSS selectors, XPath selectors, text selectors, or even custom selectors defined by the user. Once a selector is defined, Playwright can perform actions on the element it points to, such as clicking, typing, or reading text.

Elements, or more specifically ElementHandles, are objects that reference an element on a page. Once you have an ElementHandle, you can perform actions on that element, and it will ensure that the element is available and not stale. This is useful for interacting with elements that may not be immediately available due to dynamic content loading and other asynchronous behavior common in modern web applications.

The Playwright API Structure

The Playwright API is designed to be intuitive and straightforward. It mirrors the structure of a web browsing experience at a high level while providing detailed control at the lower levels. The API is organized around the following hierarchy:

  • Browser: Methods to control browser-level actions, such as launching or closing a browser.

  • BrowserContext: Methods to manage contexts, like creating new contexts or closing them, along with setting context-wide options (e.g., viewport size, geolocation, permissions).

  • Page: Methods to interact with and control a web page, like navigating to a URL, selecting elements, and executing page-level scripts.

  • ElementHandle: Methods to perform actions on individual elements, such as clicking, typing into inputs, or retrieving properties and text content.

Playwright Test Automation Cheat Sheet

Installation Guide:

  1. Ensure Node.js (version 12 or above) is installed.

  2. Run npm i -D playwright to install Playwright and browser binaries.

  3. Verify the installation with npx playwright --version.

Configuring Playwright for different browsers:

  1. Install the necessary browser binaries via npx playwright install where can be chromium, firefox, or webkit.

  2. Configure the desired browser in the script by using playwright.<browserType>().

Creating your first script:

  1. Create a new JavaScript file (e.g., firstScript.js).

  2. Import Playwright using const { chromium } = require('playwright');.

  3. Write a basic script to launch a browser, create a page, and navigate to a URL.

Basic Commands:

Launching browsers:

const browser = await chromium.launch({ headless: false }); // for visible browser

const page = await browser.newPage();

await page.goto('https://example.com');

Interacting with elements:

await page.click('button#submit');

await page.type('input[name="email"]', 'example@example.com');

await page.selectOption('select#countries', 'US');

Advanced Interactions

Dealing with frames and pop-ups:

const frame = page.frame({ name: 'frame-name' });

await frame.click('button#submit');

Uploads and downloads:

await page.setInputFiles('input[type="file"]', 'path/to/file');

const [ download ] = await Promise.all([ page.waitForEvent('download'),'

page.click('a#downloadLink') ]); // waits for download to start

Handling network conditions and events:

page.setOfflineMode(true); // To simulate offline mode await

Selectors Cheat Sheet

Common selectors and their syntax:

  • CSS: page.click('button.class')

  • XPath: page.click('//button[@id="submit"]')

  • Text: page.click('text="Submit"')

Best practices for selecting elements:

  • Use ID or class selectors when possible.

  • Avoid using indexes in selectors; prefer text content or specific attributes.

Custom selectors and functions:

await page.$('data-testid=submit-button'); // Custom attribute selector

Working with Assertions

Overview of assertions in Playwright:

  • Assertions are used to verify conditions in the browser.

  • Playwright works with assertion libraries like Chai, Jest, etc.

Common assertion examples:

const title = await page.title(); expect(title).toBe('Expected Title');

Tips for effective assertions:

  • Always wait for elements before asserting.

  • Use assertions to verify the state of the application, not just the presence of elements.

Automation Recipes

Login automation example:

await page.type('input[name="username"]', 'user'); await page.type('input[name="password"]', 'pass'); await page.click('text="Log in"');

Data scraping example:

const data = await page.evaluate(() => { // Return scraped data from page });

End-to-end test scenario:

// Example steps for an e-commerce checkout process

Debugging Playwright Scripts

Tools and techniques for debugging:

  • Use page.on('console', message => console.log(message.text())); to listen to page console events.

  • Use DEBUG=pw:api before running the script to get Playwright's API call logs.

Common errors and their solutions:

  • Element not found: Ensure the selector is correct and the element is loaded.

  • Timeout: Increase timeout or use page.waitForSelector().

Logging and reporting:

  • Use built-in page.screenshot() and page.video() for visual logs.

Integration with Test Runners

Configuring Playwright with Jest, Mocha, etc.:

  • Use playwright-test runner for Jest-like experience.

  • Use mocha with playwright for Mocha setup.

Organizing tests and suites:

  • Group tests into describe blocks and use test or it for individual tests.

Parallel execution and headless mode:

  • Enable parallel execution by configuring the test runner appropriately.

  • Run tests in headless mode for CI/CD environments.

Continuous Integration and Deployment

Setting up Playwright in CI/CD pipelines:

  • Use the playwright-github-action for GitHub Actions integration.

  • Configure environment variables for sensitive data like login credentials.

Docker integration:

  • Use Playwright's official Docker image to run tests in containers.

Best practices for CI/CD with Playwright:

  • Cache browser binaries between runs.

  • Use artifacts for storing screenshots and videos from test runs.


Official documentation: Playwright Documentation

Community forums and support: Playwright GitHub Discussions

Happy (automated) testing!


Q: What is Playwright Cheat Sheet?

A: The Playwright Cheat Sheet is a resource that provides a quick reference guide for leveraging Playwright for browser automation and testing.

Q: How can I explore the capabilities of Playwright?

A: To explore the features and capabilities of Playwright, you can refer to the official documentation and tutorials provided by the Playwright team.

Q: What are the key features of Playwright?

A: Playwright offers features such as cross-browser testing, parallel and headless execution, and the ability to automate tasks across different web platforms.

A: It is recommended to set up Playwright for automation by following the installation and setup instructions provided in the official Playwright documentation.

Q: How can I locate a specific element on a web page using Playwright?

A: You can use the Playwright API to locate elements on a web page by using methods such as 'locate', 'match', and 'explicit selection'.

Q: Can Playwright be used for mobile automation?

A: Yes, Playwright provides support for mobile automation, allowing you to automate tasks and tests on mobile platforms.

Q: What are the benefits of migrating to Playwright from other automation frameworks like Cypress?

A: Migrating to Playwright from frameworks like Cypress can offer benefits such as improved performance, broader browser support, and a more up-to-date platform for automation.

Q: How can I ensure accessibility in automated tests using Playwright?

A: You can ensure accessibility in automated tests using Playwright by leveraging features such as 'text alternative', 'accessible value await', 'label await', and 'placeholder'.

Q: Can Playwright be integrated with Git for version control?

A: Yes, Playwright can be integrated with Git for version control to manage and track changes in automation scripts and test files.

Q: How can I master Playwright for advanced automation tasks?

A: To master Playwright for advanced automation tasks, it is recommended to explore advanced features, APIs, and best practices provided by the Playwright team and community.

Q: What is async in Playwright?

A: In the Playwright framework, async ({page}) signifies a function that operates asynchronously, accepting an argument named page that denotes a web page. The use of async indicates that the function is designed to execute without hindering the concurrent running of other scripts.

Speed up the entire testing process now

Automate web app testing easier than ever. Without excessive costs. Faster than coding. Free forever.

Dominik Szahidewicz

Software Developer

Application Consultant working as a Tech Writer https://www.linkedin.com/in/dominikdurejko/

Don't miss any updates
Get more tips and product related content. Zero spam.