keepcalculator

06 Numbers and Powers

Selenium to Playwright Migration: A Practical Guide

Card No. 06·79587 · Updated · Standard formula, shown below

This guide walks you through migrating your automated browser tests from Selenium to Playwright. You’ll learn the key differences, a step-by-step conversion process, common pitfalls, and how to troubleshoot issues. By the end, you’ll have a working Playwright test suite that runs faster and more reliably.

What You’ll Need

  • An existing Selenium test suite (Java, Python, JavaScript, or C#)
  • Node.js (v16 or later) if you’re using Playwright’s JavaScript/TypeScript API
  • Or the equivalent language runtime for your chosen Playwright binding (Python, Java, .NET)
  • Basic familiarity with your current test structure and selectors

Step-by-Step

  1. Assess your current tests. List all Selenium tests and categorize them by complexity: simple element interactions, multi-page flows, file downloads, iframes, or network mocking. This helps you prioritize and spot features that may need special attention.
  2. Install Playwright. In your project directory, run npm init playwright@latest (for JS/TS) or use the equivalent package manager command for your language. This scaffolds a basic test directory and installs browsers.
  3. Understand the API differences. Playwright uses a different API than Selenium. Key mappings:
    • WebDriver → Browser + BrowserContext
    • WebElement → Locator
    • driver.findElement(By.id("foo")) → page.locator("#foo")
    • element.click() → locator.click() (with auto-waiting)
    • Thread.sleep() → expect(locator).toBeVisible() (or locator.waitFor())
  4. Rewrite your test setup. Replace Selenium’s WebDriver initialization with Playwright’s browser launch. For example, in JavaScript:
    const { chromium } = require('playwright');
    const browser = await chromium.launch();
    const page = await browser.newPage();
  5. Convert locators. Selenium’s By.xpath, By.cssSelector, By.id, etc., map to Playwright’s locator API. Playwright also supports text selectors (getByText()) and role-based selectors (getByRole()) which are more robust. Replace all findElement calls with page.locator() or the dedicated getters.
  6. Replace explicit waits. Selenium’s WebDriverWait with expected conditions becomes Playwright’s auto-waiting. Playwright automatically waits for elements to be actionable before clicking or typing. Remove all Thread.sleep() and time.sleep() calls; use expect() assertions to wait for conditions.
  7. Handle dialogs and popups. Selenium’s Alert handling is replaced by Playwright’s page.on('dialog') event. Register a listener before the action that triggers the dialog, then accept or dismiss it.
  8. Manage multiple tabs/windows. Selenium uses driver.getWindowHandles(). Playwright uses context.waitForEvent('page') to capture new pages. Use page.waitForEvent('popup') to handle popups and switch to the new page object.
  9. Handle iframes. Selenium’s driver.switchTo().frame() becomes Playwright’s frameLocator(). Use page.frameLocator('#frame-id').locator('button') to interact with elements inside iframes.
  10. Test file downloads. Selenium often relies on browser preferences. Playwright uses page.waitForEvent('download') and then download.path() or download.saveAs() to handle downloads.
  11. Network mocking. If your tests intercept network requests, replace Selenium’s browser-mob-proxy or similar with Playwright’s page.route() to fulfill or abort requests. This is built-in and much simpler.
  12. Run and debug. Execute your new tests with npx playwright test. Use the built-in trace viewer and HTML reporter to debug failures. Playwright’s inspector (npx playwright codegen) can help generate selectors interactively.
  13. Refactor for parallelization. Playwright runs tests in parallel by default. Ensure your tests are isolated (each test creates its own browser context) to avoid state leakage.

Common Mistakes

  • Keeping Selenium-style waits. Adding unnecessary waitForTimeout() calls slows tests and makes them flaky. Trust Playwright’s auto-waiting.
  • Using XPath excessively. While XPath works, CSS and text selectors are more readable and maintainable. Prefer getByRole or getByText.
  • Not using browser contexts. Each test should create a new context to isolate cookies and storage. Reusing the same page across tests causes cross-test contamination.
  • Ignoring the auto-waiting behavior. Playwright waits for elements to be visible, stable, and enabled. If you click too early, it will wait automatically—don’t try to force it with manual waits.
  • Forgetting to close the browser. Always close the browser in a finally block or use the test runner’s fixture to ensure cleanup.

Tips

  • Use Playwright’s code generator to capture selectors for tricky elements—it gives you the most robust locator.
  • Take advantage of Playwright’s built-in assertions like expect(locator).toHaveText() instead of manually reading text and comparing.
  • Leverage Playwright’s trace viewer to debug failures visually—it records screenshots, network, and console logs.
  • Use environment variables for configuration (base URL, credentials) to keep tests portable.
  • Migrate incrementally: convert one test file at a time, run it, and fix issues before moving on.

Troubleshooting

  • Element not found. Playwright’s auto-waiting will retry for a timeout. If it still fails, check the selector in the browser’s devtools. Use page.locator() with a more specific selector or use getByText() with partial text.
  • Test times out. Increase the timeout in the test config (testTimeout) or use test.setTimeout() for a specific test. Also check if there’s a network request that never resolves—use page.route() to abort unnecessary requests.
  • Dialog not handled. Ensure the page.on('dialog') listener is registered before the action that triggers it. If you miss it, Playwright throws an error. Use dialog.accept() or dialog.dismiss().
  • Popup not captured. Use Promise.all to wait for both the click and the popup event. Example: const [popup] = await Promise.all([page.waitForEvent('popup'), page.click('button')]).
  • Download fails. Make sure you wait for the download event before checking the path. Use const download = await page.waitForEvent('download') and then await download.saveAs('/path').
  • Iframe content not visible. Use frameLocator() correctly and ensure you’re not mixing page-level and frame-level locators.

Frequently Asked Questions

Can I run Selenium and Playwright tests side by side?

Yes, you can keep both in your project during migration. Just run them with different commands or in separate directories. Playwright and Selenium can coexist as long as they don’t share the same browser profile.

Is Playwright faster than Selenium?

Generally, yes. Playwright’s auto-waiting and parallel execution reduce idle time. It also uses a faster protocol (CDP) and can run tests in multiple workers without extra setup.

Do I need to rewrite all my test code?

Yes, the API is completely different. However, the logic behind your tests (what to click, what to assert) remains the same. The conversion is mostly mechanical, but you’ll also benefit from simplifying waits and using better selectors.

Does Playwright support all browsers?

Playwright supports Chromium, Firefox, and WebKit. It does not support Internet Explorer or legacy Edge. For modern web apps, this is usually sufficient.

Can I use Playwright with my existing CI/CD pipeline?

Absolutely. Playwright provides Docker images and GitHub Actions. You can also run it on Jenkins, GitLab CI, or any system that can run Node.js commands.

How do I handle authentication in Playwright?

You can store the browser context’s storage state (cookies, localStorage) and reuse it. Use context.storageState() to save and browser.newContext({ storageState: 'state.json' }) to restore.

Related

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.

More cards in this drawer

The whole Numbers and Powers drawer →