Next-Gen App & Browser
Testing Cloud

Trusted by 2 Mn+ QAs & Devs to accelerate their release cycles

Next-Gen App & Browser Testing Cloud

What Is Playwright: A Tutorial on How to Use Playwright

Explore Playwright with this tutorial! Learn how to set up and use Playwright for seamless automated testing with practical examples.

Published on: July 21 2025

  • Share:

Playwright is an open-source framework for automating and testing web applications across Chromium, Firefox, and WebKit. Due to its cross-browser support, fast execution, and robust API, it enables reliable Playwright testing across modern browsers and platforms.

What Is Playwright?

Built by Microsoft, Playwright is a Node.js library that, with a single API, automates websites and web apps running on Chromium, Firefox, and WebKit. These APIs can be used by developers writing JavaScript code to create new browser pages, navigate to URLs, and then interact with elements on a page.

In addition, since Microsoft Edge is built on the open-source Chromium web platform, Playwright can also automate Microsoft Edge.

Playwright launches a headless browser by default. The command line is the only way to use a headless browser, as it does not display a UI. Playwright also supports running full (non-headless) Microsoft Edge.

Core Features of Playwright Automation

Playwright stands out due to its cross-browser, cross-platform, and cross-language capabilities. It's trusted by developers and QA engineers for Playwright automation because of its consistent architecture, rich tooling, and flexibility for complex test scenarios.

Here’s why it’s a popular choice:

  • Cross-browser support: Supports Chromium (Chrome, Edge), WebKit (Safari), and Firefox.
  • Cross-platform compatibility: Runs on Windows, Linux, and macOS, in both headless and headed modes.
  • Multi-language support: Works with TypeScript, JavaScript, Python, .NET, and Java.
  • Mobile emulation: Native emulation for Chrome on Android and Safari on iOS.
  • Auto-waiting: Waits for elements to be ready before performing actions, eliminating the need for manual timeouts.
  • Web-first assertions: Retries checks until the required conditions are met, ideal for dynamic pages.
  • Real user interactions: Simulates native browser input for actions like typing, clicking, hovering, and scrolling, just as a real user would.
  • Out-of-process architecture: Communicates over a single persistent WebSocket connection for faster, more stable test execution.
  • Multi-tab and multi-user testing: Simulate workflows across tabs, origins, and users within the same test run.
  • Shadow DOM and iframe support: Playwright selectors can pierce deep DOM structures and handle nested frames seamlessly.
  • Context isolation: Each test runs in a fresh browser context, ensuring complete isolation between tests.
  • Authentication state reuse: Save login sessions and reuse them across tests without re-authentication.
  • Codegen: Automatically generate Playwright tests by recording your browser actions.
  • Playwright Inspector: Visually inspect, debug, and step through your tests in real time.
  • Trace Viewer: View test execution traces with videos, DOM snapshots, and logs to debug failures efficiently.
Note

Note : Now test your mobile apps with Playwright - Checkout how!

How Playwright Testing Works?

To understand how Playwright's architecture works, we’ll compare it with Selenium.

When we talk about Selenium or compare it with Playwright automation, we mean that Selenium sends each command as an independent HTTP request and receives JSON responses.

Each interaction, such as opening a browser window, clicking an element, or entering text into an input box, is sent as a separate HTTP request.


WebSocket connection

Instead of communicating with each driver through a separate WebSocket connection, Playwright relies on a single WebSocket connection to communicate with all drivers, which remains in place until testing is finished.

This allows commands to be sent quickly over one connection, reducing the points of failure and improving test stability. It's one of the reasons Playwright testing is preferred in modern automation pipelines.

How to Install Playwright Using Command Line?

Follow these steps to install Playwright manually via terminal:

  • Create a project directory: Create a folder to organize your automation files.

  • Initialize a Node.js Project: Run the command below to generate a package.json file, which is essential for managing your project’s dependencies.
  • npm init -y

  • Install Playwright: Run the command below to install Playwright and its browser binaries (Chromium, Firefox, and WebKit) as development dependencies in your project.
  • npm init playwright@latest

This sets up the foundation for your Playwright automation environment. Make sure Node.js is already installed on your system. If not, download and install it from the official Node.js website.

How to Install Playwright Using Visual Studio Code?

Follow these steps to install Playwright using Visual Studio Code:

  • Open VS Code: Launch the Visual Studio Code editor on your system.

  • Open the Extensions view: Click the Extensions icon on the sidebar, or press:
  • Ctrl + Shift + X

  • Search and install Playwright Test: Type “Playwright Test” in the search bar and install the official extension by Microsoft.
  • Run Install Playwright: After installation, open the Command Palette using:
  • Ctrl + Shift + P (or Cmd + Shift + P on macOS)
  • Then run the command:
  • Install Playwright

These steps will set up your project so you can start writing your Playwright tests.

Run Your First Playwright Test

Let’s get started with your first Playwright test case using TypeScript. For demonstration purposes, you’ll run the test locally on the LambdaTest eCommerce Playground website.

Test Scenario:

  • Locate the "Shop by Category" button on the page
  • Assert that the button is present in the DOM.
  • Assert that the aria-expanded attribute is present and its value is "false".

Code Implementation:

import { test, expect } from '@playwright/test';
test('shop by category button has aria-expanded false', async ({ page }) => {
  await page.goto('https://ecommerce-playground.lambdatest.io/');
  await expect(page.getByRole('button', { name: 'Shop by Category' })).toHaveAttribute('aria-expanded', 'false');
});

LambdaTest

Code Walkthrough:

  • Navigation: The test navigates to the LambdaTest ECommerce Playground homepage using page.goto()
  • Locator Strategy: It uses the page.getByRole() locator to find the "Shop by Category" button based on its accessible role and name.
  • Assertion: Then it applies the expect() assertion with toHaveAttribute() to verify the button has an aria-expanded attribute set to "false".

Test Execution:

To execute the tests, run the below command:

npx playwright test

The image below shows the test execution report, run the following command given below:


npx playwright show-report

playwright local execution report

Running tests on a single setup might work for small projects, but it quickly becomes limiting when dealing with larger test suites or legacy systems. To ensure consistent performance across browsers and platforms, you need a scalable solution.

LambdaTest, a GenAI-powered test execution platform, lets you run Playwright tests in parallel across 3000+ real browser and OS combinations, helping you scale your Playwright tests efficiently without managing infrastructure.

...

How to Run Playwright Tests in Parallel?

The above test scenarios have been executed on the local grid. To run the same Playwright tests on the LambdaTest cloud platform, a few additional configurations are required in your local setup.

Code Implementation:

  • Set up the environment variables: Create a .env file in your project root.
  • Add LambdaTest credentials: In the .env file, add your LambdaTest LT_USERNAME and LT_ACCESS_KEY, which you can find under LambdaTest > Account Settings > Password & Security.
  • Configure Playwright: Update your playwright.config.ts file to include conditional logic or setup to run tests either locally or on the LambdaTest Playwright grid depending on your environment.

To get started, refer to the documentation on Playwright testing with LambdaTest.

To run Playwright automation on LambdaTest, update your test script to connect via the LambdaTest WebSocket URL.


wsEndpoint: `wss://cdp.lambdatest.com/playwright?capabilities=${encodeURIComponent(JSON.stringify(capabilities))}`

Next, set your LambdaTest Username and Access Key as environment variables, and define the browser, version, platform, and other automation capabilities needed for Playwright testing.


// LambdaTest capabilities
const capabilities = {
  browserName: "Chrome", // Browsers allowed: 'Chrome', 'MicrosoftEdge', 'pw-chromium', 'pw-firefox' and 'pw-webkit'
  browserVersion: "latest",
  "LT:Options": {
    platform: "Windows 11",
    build: "Playwright Demo",
    name: "Playwright Demo",
    user: process.env.LT_USERNAME,
    accessKey: process.env.LT_ACCESS_KEY,    
    network: false,
    video: false,
    console: false    
  },
};

You can generate the required capabilities using the LambdaTest Automation Capabilities , based on your desired test setup.

Once generated, add them to your setup and then modify your test file to import the custom test method defined in the lambdatest-setup.ts file.

import { expect } from '@playwright/test';
import test from "../lambdatest-setup";

Test Execution:

Now execute the tests using the below command:

npx playwright test

Head over to the LambdaTest Web Automation Dashboard to monitor your test execution results in real time.

step-by-step test execution

Best Practices for Playwright Testing

When performing Playwright testing, here are some of the best practices you can follow:

  • Use Built-In Locators: Prefer getByRole, getByText, or getByPlaceholder instead of CSS or XPath selectors for resilient and stable tests.
  • Chain and Filter Locators: Narrow down element targets using .filter() and locator chaining to improve precision and reduce test flakiness.
  • Use Web-First Assertions: Assertions like toBeVisible() auto-wait until conditions are met, eliminating the need for manual timeouts.
  • Avoid Fragile Selectors: Don't rely on CSS classes or deeply nested DOM structures, use user-facing attributes like roles or labels.
  • Generate Locators with Codegen: Use npx playwright codegen <url> to automatically pick stable locators using Playwright's built-in tool.
  • Debug with Inspector or Trace Viewer: Run tests with --debug or --trace on to inspect element matches, network activity, and DOM snapshots.
  • Optimize CI Browser Installs: On CI, install only needed browsers with npx playwright install chromium --with-deps to save time and space.
  • Keep Playwright Updated: Regularly run npm install -D @playwright/test@latest to stay aligned with the latest browser support.
  • Use TypeScript and Linting: Use ESLint with @typescript-eslint/no-floating-promises to ensure correct async behavior in tests.

Learning Resources for Playwright Automation

You can explore the Playwright resources listed below to deepen your understanding and enhance your learning journey. These resources provide valuable insights, tutorials, and best practices that will help you gain a more comprehensive knowledge of the subject.

Articles

LambdaTest Playwright Video Tutorials

Complete Playwright Java Tutorial

Complete Playwright TypeScript Tutorial

Playwright JavaScript Tutorial

LambdaTest Playwright Certifications

In addition to the above learning resources, it’s essential to elevate your Playwright skills further.

Following are the LambdaTest Certifications in Playwright that provide a great opportunity to validate and showcase your expertise, taking your knowledge to the next level.

Frequently Asked Questions (FAQs)

What is Playwright testing?
Playwright is a Node.js library that lets you script and automates browsers using the same API, like Chrome, Firefox, and Safari. This cross-browser automation is evergreen, capable, reliable, and fast! It also lets you access the REST API of your application to help you perform API testing.
Is Playwright better than Selenium?
The Playwright performs various actionability checks on elements before performing specific actions, thereby making the execution of the tests more stable. In Selenium, we use implicit and explicit waits. The scripts are written in Playwright execute faster than those written in Selenium.
Can we use Playwright for API testing?
Yes! You can use Playwright for API testing.
What browser and OS versions does Playwright on Automate support?
LambdaTest makes testing across browsers a breeze. Run Playwright tests in parallel (across 50+ browsers and OS configurations) to cut down on test execution time further. Not only this, reduce feedback time and get your product out faster with LambdaTest.
How do I start a Playwright test?
To start a Playwright test, install Playwright, create a new file, import Playwright, and write your test using the desired browser context.
What tools does a Playwright use?
A Playwright uses automation tools like Playwright API and Playwright Test to write and execute browser automation tests, interact with web pages, and validate web app functionalities, providing efficient and reliable testing capabilities.
Does playwright need coding?
No, Playwright does not require coding. It is an end-to-end testing library that enables developers to automate actions in browsers and perform tests without extensive coding knowledge.
Is Playwright built on Selenium?
No, Playwright is not built on Selenium. It is a modern and powerful automation testing framework developed by Microsoft, offering cross-browser and cross-platform support with better performance and advanced features.
Which language is best for Playwright?
Playwright works with some of the most popular programming languages, including JavaScript, Python, Java, and C#. It also supports Chromium, Firefox, and WebKit, providing a wide range of cross-browser testing capabilities.

Did you find this page helpful?

Helpful

NotHelpful

More Related Hubs

ShadowLT Logo

Start your journey with LambdaTest

Get 100 minutes of automation test minutes FREE!!