Playwright Masters

Selenium to Playwright Migration: A Complete Step-by-Step Guide

Selenium has helped automation testers validate web applications for years. However, as applications become more dynamic and testing requirements grow, many QA teams are exploring Playwright as an alternative for browser automation.

Selenium to Playwright migration is the process of converting existing Selenium automation tests, browser interactions, framework components, and testing workflows into a Playwright-based solution while preserving the original test coverage and expected behavior.

A successful migration involves more than replacing Selenium commands with Playwright methods. Teams must review their locators, waiting strategies, assertions, test data, browser configuration, reporting, and CI/CD pipelines.

Table of Contents

This guide explains how to migrate Selenium tests to Playwright step by step, with practical code examples, framework recommendations, common challenges, and a migration checklist.

Whether you are a manual tester learning automation, an experienced Selenium engineer, an SDET, or a QA lead managing an enterprise framework, you will learn how to plan and execute a reliable migration.

Selenium to Playwright migration guide

What Is Selenium to Playwright Migration?

Selenium to Playwright migration means moving an existing browser automation suite from Selenium WebDriver to Microsoft’s Playwright automation framework.

The migration usually involves rewriting browser interactions, updating element locators, replacing unnecessary explicit waits, adapting assertions, restructuring test setup, and configuring execution and reporting.

For instance, a Selenium script can use driver.findElement() to identify a button and WebDriverWait to ensure it is ready to be clicked. In Playwright, a locator and its built-in actionability checks can often handle the same interaction with less code.

The goal is not simply to reduce the number of lines in a test. The goal is to maintain correct test behavior while making the framework easier to execute, debug, and maintain.

Why Should Teams Switch from Selenium to Playwright?

Teams generally consider migrating when their existing framework requires significant maintenance, suffers from synchronization problems, or needs better debugging and browser-testing workflows.

Playwright offers several capabilities that can address these requirements.

1. Built-in Auto-Waiting

Selenium tests often use explicit waits to handle elements that appear after a delay. Poorly designed waits can make tests slow or unreliable.

Playwright automatically checks whether elements are ready for supported actions. For example, before clicking a button, Playwright checks relevant conditions such as visibility, stability, and whether the element is enabled.

This minimizes the amount of manual waiting logic developers need to write.

2. Reliable Locator Strategies

Playwright supports locators based on accessible roles, labels, text, test IDs, and CSS selectors.

These options help testers create readable locators that reflect how users interact with an application.

For example, locating a button by its accessible name can be easier to understand than maintaining a long XPath expression.

3. Built-In Test Runner

Playwright Test provides test execution, fixtures, assertions, retries, reporting, and parallel execution features.

Teams choosing Playwright Test can use these capabilities without assembling every part of their testing infrastructure independently.

However, teams using Java, Python, or .NET should choose the appropriate Playwright binding and testing framework rather than assuming every Playwright project uses Playwright Test.

4. Browser Context Isolation

Playwright browser contexts provide isolated browser sessions without requiring a separate browser installation for every session.

This makes it easier to create independent sessions for tests involving different users, authentication states, or application data.

5. Improved Debugging

Playwright provides tools such as the Trace Viewer, screenshots, videos, and execution logs, depending on the configuration.

These tools help testers investigate failed actions, inspect page states, and understand what happened during a test.

Important: Playwright is not automatically better for every project. Selenium remains useful for existing infrastructure, language requirements, specialized browser environments, and established WebDriver-based workflows. Migration should solve a real engineering problem rather than follow a trend.

Selenium vs Playwright: What Changes During Migration?

Feature

Selenium WebDriver

Playwright

Browser automation

Uses the WebDriver protocol

Uses Playwright’s browser automation architecture

Element location

findElement() and findElements()

Locators such as locator() and getByRole()

Waiting

Explicit waits are commonly used

Supported actions and web-first assertions automatically wait

Assertions

Usually provided by a separate assertion library

Playwright Test includes web-first assertions; other bindings offer their own options

Browser sessions

WebDriver sessions

Browser contexts and pages

Browser engines

Browser and driver configuration depends on the environment

Chromium, Firefox, and WebKit support

Test runner

Commonly JUnit, TestNG, Pytest, or another runner

Playwright Test or a compatible external runner

Debugging

Logs, screenshots, and framework-specific tools

Traces, screenshots, videos, and other debugging features

Parallel execution

Depends on framework and infrastructure

Supported by Playwright Test and other compatible configurations

The main differences appear in browser setup, element location, synchronization, assertions, browser sessions, and test execution.The exact migration effort depends on the current framework, programming language, browser requirements, and test-suite size.

A small Selenium project with simple login tests may require relatively little restructuring. Migrating a large enterprise framework with custom tools, remote test execution, reporting integrations, and advanced authentication workflows may involve additional time and effort.

Step-by-Step Guide to Migrating Selenium Tests to Playwright

A reliable migration strategy involves moving tests in small stages, checking the results at each step, and retaining the existing Selenium test suite until the new Playwright tests have been thoroughly tested and confirmed to work correctly.

Step 1: Audit the Existing Selenium Framework

Before developing Playwright tests, review your existing Selenium framework to understand its functionality and structure.

Review the following components:

  • Total number of automated tests.
  • Programming language and test runner.
  • Page Object Model implementation.
  • Locators and custom element utilities.
  • Explicit waits and synchronization methods.
  • Authentication and session management.
  • Test data and environment configuration.
  • Screenshots, reports, and logging.
  • CI/CD workflows and browser infrastructure.
  • External libraries and framework dependencies.

Classify the tests into groups such as smoke tests, regression tests, authentication tests, critical business workflows, and less frequently executed scenarios.

Identify flaky tests separately. A test that fails frequently in Selenium should not be copied blindly into Playwright.

First determine whether the problem comes from unstable locators, application defects, incorrect test data, timing assumptions, or genuine environment failures.

Migration tip: Record the existing test coverage and important expected results before rewriting the tests. This gives your team a reference for validating the new framework.

Step 2: Select the Playwright Programming Language and Test Framework

Playwright allows teams to write automated tests using JavaScript, TypeScript, Java, Python, or .NET.

Choose the language based on your team’s existing skills, project requirements, and the capabilities needed for your test infrastructure.

For example:

  • Choose TypeScript if your team works extensively with JavaScript applications and wants static type checking.
  • Choose Java if your organization has substantial Java expertise and prefers to retain its existing language.
  • If your testing team already works with Python-based automation tools, selecting Python for Playwright can make the transition easier.
  • Choose .NET if your organization relies on C# and Microsoft development technologies.

Also decide whether to use Playwright Test or an external test runner supported by your chosen language binding.

For a TypeScript project using Playwright Test, the initial setup can be created using:

npm init playwright@latest

 

Follow the setup prompts and install the required browser binaries.

Do not assume that installing Playwright completes the migration. You still need to configure the project, move the tests, update dependencies, and verify that the framework runs correctly.

Step 3: Migrate Browser Initialization and Navigation

Selenium and Playwright use different APIs to create browser sessions and navigate to pages.

Selenium with Java:

WebDriver driver = new ChromeDriver();

driver.get(“https://example.com”);

 

Playwright with TypeScript:

import { test } from ‘@playwright/test’;

 

test(‘open the application’, async ({ page }) => {

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

});

 

The Playwright example uses the built-in page fixture provided by Playwright Test.

The fixture manages the page lifecycle for the test. With Playwright’s built-in fixture system, you can manage browser setup and cleanup automatically instead of manually opening and closing a browser in every test.

For a project using Java, Python, or .NET, follow the equivalent setup and lifecycle pattern for that language.

Step 4: Convert Selenium Locators to Playwright Locators

Locator migration is one of the most important parts of the conversion process.

Selenium projects frequently use ID, CSS, XPath, and other locator strategies. Playwright supports many of these strategies but also encourages locators based on accessible roles and labels.

Consider a login form.

Selenium with Java:

driver.findElement(By.id(“username”)).sendKeys(“testuser”);

 

driver.findElement(By.id(“password”)).sendKeys(“password”);

 

driver.findElement(By.id(“login”)).click();

 

Playwright with TypeScript:

await page.locator(‘#username’).fill(‘testuser’);

 

await page.locator(‘#password’).fill(‘password’);

 

await page.locator(‘#login’).click();

 

This example preserves the original ID-based approach.

If the application has accessible labels, you can often make the test more descriptive:

await page.getByLabel(‘Username’).fill(‘testuser’);

 

await page.getByLabel(‘Password’).fill(‘password’);

 

await page.getByRole(‘button’, { name: ‘Login’ }).click();

 

These locators depend on the application’s actual labels and accessible names. Adjust them to match the real interface.

Avoid converting every XPath into another long selector without reviewing its purpose. Migration is an opportunity to replace brittle locators with clearer, more maintainable alternatives.

For more practical examples, connect this article to the PlaywrightMasters guides on Playwright Locators and Playwright Assertions.

Step 5: Replace Unnecessary Explicit Waits

One of the main differences between Selenium and Playwright is how they handle synchronization during test execution.

A Selenium test may wait explicitly for a button before clicking it.

Selenium with Java:

WebDriverWait wait = new WebDriverWait(

    driver,

    Duration.ofSeconds(10)

);

 

WebElement button = wait.until(

    ExpectedConditions.elementToBeClickable(

        By.id(“submit”)

    )

);

 

button.click();

 

Playwright with TypeScript:

await page.locator(‘#submit’).click();

 

Playwright waits for the locator to satisfy the relevant actionability requirements before performing the click.

However, review each waiting condition carefully before removing it from the migrated tests.

If a test depends on a specific business event, network response, navigation, or application state, it may still need an appropriate synchronization strategy.

For example, when submitting a form triggers a particular API request, the test can wait for the expected response and then verify the visible result.

Avoid using fixed delays such as waitForTimeout() as a general replacement for Selenium waits. Fixed delays can make tests slower and still fail when the application takes longer than expected.

Step 6: Migrate Assertions Carefully

A test is useful only when it checks the correct result.

During migration, preserve the original business expectation instead of merely translating assertion syntax.

Selenium with Java:

String actualTitle = driver.getTitle();

 

Assert.assertEquals(

    actualTitle,

    “Dashboard”

);

 

Playwright with TypeScript:

import { test, expect } from ‘@playwright/test’;

 

test(‘dashboard title is correct’, async ({ page }) => {

  await page.goto(‘https://example.com/dashboard’);

 

  await expect(page).toHaveTitle(‘Dashboard’);

});

 

The Playwright assertion automatically retries until the expected title matches or the assertion times out.

When migrating assertions, review whether the original test checks the correct outcome.

For example, a login test should not pass simply because the login button was clicked. It should verify that the user reached the expected authenticated state.

Useful checks include the dashboard heading, account name, expected URL, or another reliable indicator of successful login.

Step 7: Rebuild the Page Object Model

Many Selenium frameworks use the Page Object Model, or POM, to separate page interactions from test logic.

You can retain this design when migrating to Playwright. However, the page objects should use Playwright’s APIs and follow the lifecycle conventions of the chosen framework.

A simple TypeScript page object might look like this:

import { Page, Locator } from ‘@playwright/test’;

 

export class LoginPage {

  readonly username: Locator;

  readonly password: Locator;

  readonly loginButton: Locator;

 

  constructor(private page: Page) {

    this.username = page.locator(‘#username’);

    this.password = page.locator(‘#password’);

    this.loginButton = page.locator(‘#login’);

  }

 

  async login(

    username: string,

    password: string

  ) {

    await this.username.fill(username);

    await this.password.fill(password);

    await this.loginButton.click();

  }

}

 

This page object stores locators and groups the login actions into one reusable method.

Tests can reuse the login() method across different scenarios instead of duplicating the same login steps in every test.

Keep page objects focused on page behavior. Test-specific assertions, business rules, test data, and setup logic should remain organized in appropriate layers rather than being placed everywhere in the framework.

Explore the Page Object Model in the PlaywrightMasters guide to learn more about this design pattern.

Step 8: Migrate Authentication, Cookies, and Browser Sessions

Authentication can become a major challenge when moving an established framework.

Review how the Selenium tests currently log in, store cookies, reuse sessions, handle multiple users, and manage authentication tokens.

Playwright provides browser contexts that can isolate sessions and support authentication-state reuse.

For suitable applications, Playwright can save and restore authentication state. This may reduce repeated login steps across tests.

However, authentication state can contain sensitive cookies or tokens. Store these files securely, avoid uploading them to public repositories, and allow access only to approved testing environments.

Do not reuse authentication state blindly when tests depend on different permissions, user roles, or session conditions.

For applications involving several users, create separate browser contexts where appropriate so that one test does not accidentally affect another test’s session.

Step 9: Update Test Data, Fixtures, and Configuration

Your existing Selenium framework may contain reusable setup methods, environment variables, database helpers, test-data factories, and reporting utilities.

Review each component before migrating it.

Some utilities can remain unchanged because they do not depend on Selenium. Others must be redesigned to work with Playwright.

If you use Playwright Test, fixtures can provide reusable setup and teardown logic for pages, authentication, test data, and other dependencies.

Store environment-specific values in configuration or environment variables instead of hard-coding production credentials and URLs into test files.

Also define how the framework will handle:

  • Test timeouts and assertion timeouts.
  • Retries and failure reporting.
  • Browser projects and supported engines.
  • Parallel workers and shared resources.
  • Test-data cleanup.
  • Screenshots, traces, and reports.

For more information, link this section to the Playwright Fixtures guide and the Playwright Roadmap.

Step 10: Integrate Playwright with CI/CD

After the migrated tests work locally, integrate them into your continuous integration and continuous delivery pipeline.

The CI/CD pipeline should install all necessary dependencies and browsers, run the automated tests, and save debugging files whenever a test fails.

For a Node.js project, a basic execution sequence might include:

npm ci

npx playwright install –with-deps

npx playwright test

 

The commands may vary depending on the package manager, operating system, CI platform, and project setup.

During the transition, run the existing Selenium tests and the new Playwright tests in parallel where practical.

Compare their outcomes on the same application version and equivalent test data. Investigate differences instead of assuming the new result is automatically correct.

Once the Playwright suite demonstrates reliable coverage, gradually remove the corresponding Selenium jobs and dependencies.

Common Selenium to Playwright Migration Challenges

Understanding common migration problems helps prevent avoidable failures.

1. Copying Selenium Waits Directly

Problem: The migrated tests still contain unnecessary fixed delays and complicated waiting logic.

Solution: Use Playwright’s built-in actionability checks and web-first assertions. Add explicit synchronization only when a meaningful application condition requires it.

2. Reusing Fragile Locators

Problem: Old XPath expressions depend on page structure that frequently changes.

Solution: Review each locator and prefer stable, accessible selectors where possible. Use test IDs when the application provides them specifically for automation.

3. Changing the Test Language Too Early

Problem: The team changes programming languages, test runners, reporting, and framework architecture simultaneously.

Solution: Evaluate the migration goals first. Whenever possible, avoid making unnecessary changes so that any test failures can be linked to the migration rather than multiple simultaneous updates.

4. Sharing Browser State Between Tests

Problem: One test changes a session or application state and causes another test to fail.

Solution: Use appropriate browser-context isolation, independent test data, and reliable cleanup procedures.

5. Migrating Tests Without Checking Coverage

Problem: The migrated tests pass, but they fail to check essential business rules and requirements.

Solution: Compare assertions and expected outcomes with the original tests. Track coverage by user journey and business function, not just the number of converted files.

6. Assuming Playwright Always Runs Faster

Problem: The team expects automatic performance improvements without measuring execution time.

Solution: Benchmark representative tests before and after migration. Investigate worker settings, application performance, shared resources, test data, and CI machine capacity.

Playwright may help tests run more efficiently, but the results vary based on the application and how the testing framework is designed.

How Long Does Selenium to Playwright Migration Take?

There is no universal migration timeline because two test suites with the same number of tests can have very different levels of complexity.

The time required depends on the number of scenarios, framework design, programming language, custom utilities, authentication requirements, CI/CD integrations, and available engineering resources.

A small suite with straightforward browser interactions may be migrated relatively quickly. A large enterprise framework with extensive integrations may require multiple migration phases.

Estimate the effort by measuring a representative pilot rather than relying only on test count.

Record how long it takes to migrate, debug, validate, and integrate a small group of tests. Use that information to estimate the remaining work and include additional time for complex workflows and framework changes.

A realistic migration plan should include time for regression validation, team training, CI configuration, documentation, and removal of obsolete Selenium code.

Selenium to Playwright Migration Checklist

Review the following checklist to confirm that the migration is complete and ready for use.

Planning

  • Existing Selenium tests have been inventoried.
  • Critical user journeys have been identified.
  • The Playwright language and test runner have been selected.
  • Baseline execution results and test coverage have been recorded.

Code migration

  • Browser setup and navigation have been updated.
  • Locators have been reviewed and converted.
  • Unnecessary explicit waits have been removed.
  • Assertions preserve the original test expectations.
  • Page objects and shared utility functions have been successfully transferred to Playwright.
  • Authentication and browser-context handling have been validated.

Execution and quality

  • Tests pass using the expected application environment.
  • Failed tests provide useful debugging information.
  • Test data and shared resources are properly organized and maintained.
  • Browser coverage matches the project’s requirements.
  • Parallel execution has been tested safely.

Release and maintenance

  • CI/CD executes the migrated tests.
  • Reports and failure artifacts are available.
  • The team understands the new framework.
  • Test coverage has been compared against Selenium.
  • Obsolete Selenium jobs and dependencies are removed only when safe.

Frequently Asked Questions

Can Selenium tests be converted to Playwright automatically?

Some parts of Selenium test code can be converted using scripts, code-generation tools, or AI-assisted development tools. However, automatic conversion cannot reliably determine every application’s business rules, synchronization requirements, test-data dependencies, or framework-specific behavior.

Review and execute the converted tests before accepting them.

Is Playwright better than Selenium for automation testing?

Playwright offers built-in auto-waiting, browser contexts, tracing, and an integrated test runner for teams using Playwright Test. Selenium remains valuable for existing WebDriver infrastructure, specialized requirements, and established automation frameworks.

The best choice depends on the project’s technical needs rather than one framework being universally superior.

Do You Need to Rebuild Your Entire Selenium Framework?

 

Not necessarily. You can migrate incrementally, retaining useful language-independent utilities and adapting reusable components where practical.

However, browser interactions and dependencies designed specifically for Selenium usually need to be modified or rebuilt for Playwright.

 

Can I use Page Object Model with Playwright?

Yes. Page Object Model is compatible with Playwright. A well-designed page object can store locators and reusable page actions, helping tests remain readable and maintainable.

Should I migrate all Selenium tests at once?

Usually, a phased migration is safer. Start with a representative group of tests, validate the new approach, and expand to critical user journeys and other test categories.

Keeping both frameworks available during the transition can help teams compare results and reduce migration risk.

What should I learn before migrating to Playwright?

Learn locators, assertions, browser contexts, auto-waiting, test organization, fixtures, and debugging. Familiarity with the programming language selected for your project is also important.

A structured learning plan enables Selenium engineers to understand Playwright’s core differences and apply modern automation testing practices effectively.

Conclusion

Moving from Selenium to Playwright gives teams a chance to strengthen browser automation, simplify synchronization, isolate tests more effectively, improve debugging, and optimize test execution.

The most reliable approach begins with an audit of the existing Selenium suite, followed by language and framework selection, gradual test conversion, locator improvements, assertion validation, and CI/CD integration.

Avoid treating migration as a simple syntax replacement. Preserve the behavior that each test is designed to verify, measure the results, and expand only after the migrated tests demonstrate reliable coverage.

Explore the hands-on tutorials and practical learning resources on PlaywrightMasters to deepen your understanding of Playwright automation testing. They can help you progress from core Playwright concepts to framework design and real-world automation practices.

Start with one important Selenium workflow, migrate it carefully, and use the lessons from that pilot to build a more maintainable Playwright automation framework.

Playwright Masters automation testing logo - White Back ground

Playwright Masters Team

Playwright Automation Testing Experts | Industry-Focused Training & Practical Learning

Playwright Masters is a dedicated automation testing training platform focused on helping learners build practical skills in Playwright automation testing. Our training covers real-world automation concepts, framework practices, coding, debugging, API testing, cross-browser testing, CI/CD, and interview preparation to help learners develop job-ready testing skills.

Scroll to Top

Start Your Playwright Automation Career Today

Get FREE Demo + Syllabus & Become Job-Ready in Playwright.