playwright
Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.
Top Related Projects
JavaScript API for Chrome and Firefox
Fast, easy and reliable testing for anything that runs in a browser.
A browser automation framework and ecosystem.
Next-gen browser and mobile automation test framework for Node.js
Cross-platform automation framework for all kinds of apps, built on top of the W3C WebDriver protocol
Quick Overview
Playwright is a powerful automation library for web testing and scraping, developed by Microsoft. It provides a single API to automate Chromium, Firefox, and WebKit browsers, enabling cross-browser web automation that is reliable and fast.
Pros
- Cross-browser support (Chromium, Firefox, WebKit) with a single API
- Fast and reliable automation with auto-wait functionality
- Powerful tools for debugging and tracing
- Supports multiple programming languages (JavaScript, TypeScript, Python, .NET, Java)
Cons
- Steeper learning curve compared to some other automation tools
- Larger package size due to bundled browser binaries
- May require more system resources than lighter alternatives
- Limited support for older browser versions
Code Examples
- Basic page navigation and screenshot:
const { chromium } = require('playwright');
(async () => {
const browser = await chromium.launch();
const page = await browser.newPage();
await page.goto('https://example.com');
await page.screenshot({ path: 'screenshot.png' });
await browser.close();
})();
- Interacting with page elements:
const { firefox } = require('playwright');
(async () => {
const browser = await firefox.launch();
const page = await browser.newPage();
await page.goto('https://example.com/login');
await page.fill('input[name="username"]', 'myuser');
await page.fill('input[name="password"]', 'mypassword');
await page.click('button[type="submit"]');
await browser.close();
})();
- Handling multiple pages:
const { webkit } = require('playwright');
(async () => {
const browser = await webkit.launch();
const context = await browser.newContext();
const page1 = await context.newPage();
const page2 = await context.newPage();
await page1.goto('https://example.com');
await page2.goto('https://another-example.com');
// Interact with both pages...
await browser.close();
})();
Getting Started
To get started with Playwright, follow these steps:
- Install Playwright:
npm init playwright@latest
- Create a new test file (e.g.,
example.spec.js
):
const { test, expect } = require('@playwright/test');
test('basic test', async ({ page }) => {
await page.goto('https://playwright.dev/');
const title = page.locator('.navbar__inner .navbar__title');
await expect(title).toHaveText('Playwright');
});
- Run the test:
npx playwright test
This will install Playwright, create a basic test, and run it across all supported browsers.
Competitor Comparisons
JavaScript API for Chrome and Firefox
Pros of Puppeteer
- Mature ecosystem with extensive documentation and community support
- Native integration with Chrome DevTools Protocol
- Simpler setup for projects primarily targeting Chrome/Chromium
Cons of Puppeteer
- Limited cross-browser support (primarily Chrome/Chromium)
- Slower test execution compared to Playwright
- Less comprehensive API for handling modern web features
Code Comparison
Puppeteer:
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://example.com');
await page.screenshot({path: 'screenshot.png'});
await browser.close();
Playwright:
const browser = await playwright.chromium.launch();
const page = await browser.newPage();
await page.goto('https://example.com');
await page.screenshot({path: 'screenshot.png'});
await browser.close();
Both Puppeteer and Playwright are powerful tools for browser automation and testing. Puppeteer excels in Chrome-specific scenarios and has a more established ecosystem. Playwright offers better cross-browser support, faster execution, and a more comprehensive API for modern web applications. The code structure is similar, making it relatively easy to migrate between the two if needed.
Fast, easy and reliable testing for anything that runs in a browser.
Pros of Cypress
- Easier setup and configuration, with a more user-friendly interface
- Built-in time travel and debugging features
- Strong community support and extensive documentation
Cons of Cypress
- Limited cross-browser testing capabilities (primarily focused on Chrome)
- Slower test execution compared to Playwright
- Less flexibility in handling iframes and multiple tabs
Code Comparison
Cypress:
describe('Login', () => {
it('should log in successfully', () => {
cy.visit('/login')
cy.get('#username').type('user@example.com')
cy.get('#password').type('password123')
cy.get('button[type="submit"]').click()
cy.url().should('include', '/dashboard')
})
})
Playwright:
test('should log in successfully', async ({ page }) => {
await page.goto('/login')
await page.fill('#username', 'user@example.com')
await page.fill('#password', 'password123')
await page.click('button[type="submit"]')
await expect(page).toHaveURL(/.*dashboard/)
})
Both frameworks offer similar syntax for common testing scenarios, but Playwright uses async/await for better control flow. Cypress provides a more chainable API, while Playwright offers a more flexible and powerful approach to handling asynchronous operations.
A browser automation framework and ecosystem.
Pros of Selenium
- Wider language support (Java, Python, C#, Ruby, JavaScript, etc.)
- Larger community and ecosystem with extensive third-party tools and resources
- Better suited for legacy browser testing (IE, older versions)
Cons of Selenium
- Slower test execution compared to Playwright
- More complex setup and configuration
- Less robust handling of modern web features (shadow DOM, iframes)
Code Comparison
Selenium (Python):
from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
driver.get("https://example.com")
element = driver.find_element(By.ID, "my-element")
element.click()
Playwright (Python):
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch()
page = browser.new_page()
page.goto("https://example.com")
page.click("#my-element")
Both Selenium and Playwright are popular choices for browser automation and testing. Selenium has been around longer and offers broader language support, while Playwright provides better performance and easier handling of modern web technologies. The choice between the two depends on specific project requirements and team preferences.
Next-gen browser and mobile automation test framework for Node.js
Pros of WebdriverIO
- Supports a wider range of browsers and devices, including mobile platforms
- More extensive ecosystem with numerous plugins and integrations
- Longer history and larger community, potentially leading to better support
Cons of WebdriverIO
- Steeper learning curve, especially for beginners
- Slower test execution compared to Playwright
- More complex setup and configuration process
Code Comparison
WebdriverIO:
describe('My Login application', () => {
it('should login with valid credentials', async () => {
await browser.url('https://example.com/login');
await $('#username').setValue('myuser');
await $('#password').setValue('mypassword');
await $('button[type="submit"]').click();
await expect($('#logged-in-message')).toBeExisting();
});
});
Playwright:
test('should login with valid credentials', async ({ page }) => {
await page.goto('https://example.com/login');
await page.fill('#username', 'myuser');
await page.fill('#password', 'mypassword');
await page.click('button[type="submit"]');
await expect(page.locator('#logged-in-message')).toBeVisible();
});
Both WebdriverIO and Playwright are powerful tools for automated testing, with Playwright offering a more modern and streamlined approach, while WebdriverIO provides broader compatibility and a rich ecosystem. The choice between them depends on specific project requirements and team preferences.
Cross-platform automation framework for all kinds of apps, built on top of the W3C WebDriver protocol
Pros of Appium
- Supports a wider range of mobile platforms, including iOS, Android, and Windows
- Allows testing of native, hybrid, and mobile web applications
- Uses standard WebDriver protocol, making it easier for those familiar with Selenium
Cons of Appium
- Generally slower test execution compared to Playwright
- More complex setup and configuration process
- Less robust support for modern web technologies and features
Code Comparison
Appium (JavaScript):
const driver = await wdio.remote(capabilities);
await driver.setImplicitTimeout(5000);
await driver.$('~myButton').click();
await driver.deleteSession();
Playwright (JavaScript):
const browser = await playwright.chromium.launch();
const page = await browser.newPage();
await page.goto('https://example.com');
await page.click('button');
await browser.close();
While both frameworks allow for automated testing, Playwright's API is more modern and concise, focusing on web technologies. Appium's API is geared towards mobile testing and uses a different set of commands and selectors.
Playwright offers better performance and easier setup for web testing, while Appium excels in cross-platform mobile testing scenarios. The choice between the two depends on the specific testing requirements and target platforms of the project.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
ð Playwright
Documentation | API reference
Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API. Playwright is built to enable cross-browser web automation that is ever-green, capable, reliable and fast.
Linux | macOS | Windows | |
---|---|---|---|
Chromium 129.0.6668.29 | :white_check_mark: | :white_check_mark: | :white_check_mark: |
WebKit 18.0 | :white_check_mark: | :white_check_mark: | :white_check_mark: |
Firefox 130.0 | :white_check_mark: | :white_check_mark: | :white_check_mark: |
Headless execution is supported for all browsers on all platforms. Check out system requirements for details.
Looking for Playwright for Python, .NET, or Java?
Installation
Playwright has its own test runner for end-to-end tests, we call it Playwright Test.
Using init command
The easiest way to get started with Playwright Test is to run the init command.
# Run from your project's root directory
npm init playwright@latest
# Or create a new project
npm init playwright@latest new-project
This will create a configuration file, optionally add examples, a GitHub Action workflow and a first test example.spec.ts. You can now jump directly to writing assertions section.
Manually
Add dependency and install browsers.
npm i -D @playwright/test
# install supported browsers
npx playwright install
You can optionally install only selected browsers, see install browsers for more details. Or you can install no browsers at all and use existing browser channels.
Capabilities
Resilient ⢠No flaky tests
Auto-wait. Playwright waits for elements to be actionable prior to performing actions. It also has a rich set of introspection events. The combination of the two eliminates the need for artificial timeouts - a primary cause of flaky tests.
Web-first assertions. Playwright assertions are created specifically for the dynamic web. Checks are automatically retried until the necessary conditions are met.
Tracing. Configure test retry strategy, capture execution trace, videos and screenshots to eliminate flakes.
No trade-offs ⢠No limits
Browsers run web content belonging to different origins in different processes. Playwright is aligned with the architecture of the modern browsers and runs tests out-of-process. This makes Playwright free of the typical in-process test runner limitations.
Multiple everything. Test scenarios that span multiple tabs, multiple origins and multiple users. Create scenarios with different contexts for different users and run them against your server, all in one test.
Trusted events. Hover elements, interact with dynamic controls and produce trusted events. Playwright uses real browser input pipeline indistinguishable from the real user.
Test frames, pierce Shadow DOM. Playwright selectors pierce shadow DOM and allow entering frames seamlessly.
Full isolation ⢠Fast execution
Browser contexts. Playwright creates a browser context for each test. Browser context is equivalent to a brand new browser profile. This delivers full test isolation with zero overhead. Creating a new browser context only takes a handful of milliseconds.
Log in once. Save the authentication state of the context and reuse it in all the tests. This bypasses repetitive log-in operations in each test, yet delivers full isolation of independent tests.
Powerful Tooling
Codegen. Generate tests by recording your actions. Save them into any language.
Playwright inspector. Inspect page, generate selectors, step through the test execution, see click points and explore execution logs.
Trace Viewer. Capture all the information to investigate the test failure. Playwright trace contains test execution screencast, live DOM snapshots, action explorer, test source and many more.
Looking for Playwright for TypeScript, JavaScript, Python, .NET, or Java?
Examples
To learn how to run these Playwright Test examples, check out our getting started docs.
Page screenshot
This code snippet navigates to Playwright homepage and saves a screenshot.
import { test } from '@playwright/test';
test('Page Screenshot', async ({ page }) => {
await page.goto('https://playwright.dev/');
await page.screenshot({ path: `example.png` });
});
Mobile and geolocation
This snippet emulates Mobile Safari on a device at given geolocation, navigates to maps.google.com, performs the action and takes a screenshot.
import { test, devices } from '@playwright/test';
test.use({
...devices['iPhone 13 Pro'],
locale: 'en-US',
geolocation: { longitude: 12.492507, latitude: 41.889938 },
permissions: ['geolocation'],
})
test('Mobile and geolocation', async ({ page }) => {
await page.goto('https://maps.google.com');
await page.getByText('Your location').click();
await page.waitForRequest(/.*preview\/pwa/);
await page.screenshot({ path: 'colosseum-iphone.png' });
});
Evaluate in browser context
This code snippet navigates to example.com, and executes a script in the page context.
import { test } from '@playwright/test';
test('Evaluate in browser context', async ({ page }) => {
await page.goto('https://www.example.com/');
const dimensions = await page.evaluate(() => {
return {
width: document.documentElement.clientWidth,
height: document.documentElement.clientHeight,
deviceScaleFactor: window.devicePixelRatio
}
});
console.log(dimensions);
});
Intercept network requests
This code snippet sets up request routing for a page to log all network requests.
import { test } from '@playwright/test';
test('Intercept network requests', async ({ page }) => {
// Log and continue all network requests
await page.route('**', route => {
console.log(route.request().url());
route.continue();
});
await page.goto('http://todomvc.com');
});
Resources
Top Related Projects
JavaScript API for Chrome and Firefox
Fast, easy and reliable testing for anything that runs in a browser.
A browser automation framework and ecosystem.
Next-gen browser and mobile automation test framework for Node.js
Cross-platform automation framework for all kinds of apps, built on top of the W3C WebDriver protocol
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot