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
- 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.
- 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. - Understand the API differences. Playwright uses a different API than Selenium. Key mappings:
WebDriver→Browser+BrowserContextWebElement→Locatordriver.findElement(By.id("foo"))→page.locator("#foo")element.click()→locator.click()(with auto-waiting)Thread.sleep()→expect(locator).toBeVisible()(orlocator.waitFor())
- 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(); - 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 allfindElementcalls withpage.locator()or the dedicated getters. - Replace explicit waits. Selenium’s
WebDriverWaitwith expected conditions becomes Playwright’s auto-waiting. Playwright automatically waits for elements to be actionable before clicking or typing. Remove allThread.sleep()andtime.sleep()calls; useexpect()assertions to wait for conditions. - Handle dialogs and popups. Selenium’s
Alerthandling is replaced by Playwright’spage.on('dialog')event. Register a listener before the action that triggers the dialog, then accept or dismiss it. - Manage multiple tabs/windows. Selenium uses
driver.getWindowHandles(). Playwright usescontext.waitForEvent('page')to capture new pages. Usepage.waitForEvent('popup')to handle popups and switch to the new page object. - Handle iframes. Selenium’s
driver.switchTo().frame()becomes Playwright’sframeLocator(). Usepage.frameLocator('#frame-id').locator('button')to interact with elements inside iframes. - Test file downloads. Selenium often relies on browser preferences. Playwright uses
page.waitForEvent('download')and thendownload.path()ordownload.saveAs()to handle downloads. - 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. - 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. - 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
getByRoleorgetByText. - 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
finallyblock 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 usegetByText()with partial text. - Test times out. Increase the timeout in the test config (
testTimeout) or usetest.setTimeout()for a specific test. Also check if there’s a network request that never resolves—usepage.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. Usedialog.accept()ordialog.dismiss(). - Popup not captured. Use
Promise.allto 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 thenawait 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
- Arctic Sea Ice Forecasts Disagree: What to Do
- MySQL Workbench to VPS: SSH Tunnel Setup
- Bluesky Beginners Guide: How to Get Started5.00 min/km
- LG V20 Won’t Turn On? Fixed
- Snagit vs Camtasia: Which One Do You Need?
- Scale a Small Business Without Losing Culture