Migrating from Selenium to Playwright: A Guide for Teams

Supercharge your Next.js app testing with Playwright – a tool for automating Chromium, Firefox, and WebKit browsers. In this guide, I will walk you through setting up and running your first Playwright E2E test for a Next.js application.
  1. Selenium vs Playwright: A Transition Guide
    1. Differences Between Selenium and Playwright
      1. Setting up Playwright
        1. Converting Selenium Scripts to Playwright
          1. Migrating Tests from Selenium to Playwright
            1. Challenges and Solutions During Migration
              1. Migration from Selenium to Playwright

                Selenium vs Playwright: A Transition Guide

                The ongoing quest for software testing efficiency has brought Selenium and Playwright into focus. Selenium, a widely-used UI testing tool, has been beneficial. However, newer technologies like Playwright have shown advantages in speed and flexibility[1][3].

                Comparative studies revealed Playwright's superior speed over Selenium and other browser automation libraries such as Cypress, Webdriver.IO, Robot, and TestCafe. In one study, Playwright's testing speed was 264% faster than Selenium, a compelling reason for the transition from Selenium to Playwright[1].

                Selenium's operating mechanism involves a webdriver that turns test cases into JSON and sends them to the browser. In contrast, Playwright uses a direct websocket connection, giving it more control over browsers and resulting in improved speed[1][2].

                While Selenium supports multiple programming languages including C#, Playwright is primarily designed for JavaScript and TypeScript. The switch posed some challenges due to varying familiarity levels with TypeScript and Node. However, well-designed software patterns in the Playwright framework have lowered the entry barrier[1][2].

                There's a clear need to shift to a faster, more flexible tool like Playwright. While the transition is ongoing and seen as a side project, it's making steady progress[1]. This article discusses the steps for this shift, potential challenges, and solutions, aiming to enable a successful transition from Selenium to Playwright for a more advanced testing strategy.

                Differences Between Selenium and Playwright

                Selenium and Playwright are differentially designed frameworks. Selenium uses a webdriver to convert test cases into JSON and forwards them to the browser[1] while Playwright employs a websocket connection for direct control of the browsers, which aids in faster performance[1].

                Selenium is extensively usable with popular end-user browsers like Chrome, Edge, Safari, and others, while Playwright efficiently works with browser engines like Chromium and Webkit, enhancing its speed and adaptiveness[1]. Selenium's language use is generally C#. In contrast, Playwright utilizes TypeScript[1]. This language switch may pose initial hurdles for engineers not proficient in TypeScript and Node[1], but strategic software design patterns can ease the transition[1].

                Despite being newer in automated web scraping, Playwright offers superior documentation[2], a distinct advantage. However, Playwright is primarily designed for JavaScript[2].

                Installation wise, Selenium requires a browser, a webdriver, and Selenium itself[2]. Playwright, on the other hand, needs a browser but no separate webdriver[2]. Playwright is intrinsically asynchronous, performing multiple tasks simultaneously, requiring the await function for sequence control[2].

                await function_name();

                Despite potential migration challenges like API differences and varying waiting strategies[3], the transition from Selenium to Playwright signifies faster execution, consistency across browsers, native browser support, and improved debugging[3]. Thus, Playwright is viewed as faster, adaptable, and more potent than Selenium, simplifying the crafting of valuable, high-quality, and reliable tests[1].

                Setting up Playwright

                Playwright, primarily built for JavaScript and TypeScript, does not require a separate webdriver like Selenium but needs a browser. Setting it up involves installation and configuration. Begin the installation by executing the following command:

                npm install playwright

                Where 'npm' is your package manager, it can be replaced with 'yarn' if required.

                Post-installation, import the commands 'asyncio' and 'async_playwright':

                import asyncio
                from playwright.async_api import async_playwright

                Playwright offers two ways to run testing scripts. It can either present the browser window during scraping or run in "headless" mode. Here is the code to display the browser window:

                playwright = await async_playwright().start()
                browser = await playwright.chromium.launch(headless = False)
                page = await browser.new_page()
                await page.goto('https://www.nytimes.com')

                Conversely, to make it run headless, set the 'headless' option to 'True':

                playwright = await async_playwright().start()
                browser = await playwright.chromium.launch(headless = True)
                page = await browser.new_page()
                await page.goto('https://www.nytimes.com')

                Playwright is asynchronous and can execute multiple procedures concurrently. The 'await' keyword is used to pause the program until the ongoing asynchronous function is completed.

                Once set up, Playwright offers benefits such as faster execution, consistent behaviour across browsers, enhanced debugging, proficient error handling, and modern features like automatic waits and timeouts.

                When implementing Playwright, remember to apply good software design patterns for enhanced maintainability, especially if your team lacks familiarity with Node or TypeScript.

                The next phase will involve converting Selenium scripts to Playwright. Having a concrete understanding of Playwright's operation eases the migration from Selenium to Playwright.

                Converting Selenium Scripts to Playwright

                To transition from Selenium to Playwright, use the tool ray.run/tools/selenium-to-playwright. This tool aids in transforming Selenium scripts into Playwright's script format.

                Understanding and implementing asynchronous commands in Playwright is crucial in this conversion process. Unlike Selenium, Playwright can execute multiple actions concurrently, enhancing speed in script execution. The await keyword is typically used to allow the program to finish the asynchronous function before proceeding.

                The interaction with browsers in Playwright is more direct and faster than Selenium. Selenium translates test cases into JSON and sends them to the browser to execute via a webdriver. In contrast, Playwright controls browsers directly through a WebSocket connection.

                Converting from Selenium to Playwright requires more than just copying and pasting scripts. A key understanding of the fundamental differences in both frameworks is essential for setting up, writing scripts, and running tests on Playwright.

                Despite the initial learning curve, the conversion to Playwright is considered beneficial. It offers more flexibility and speed in scripting and execution, facilitating the creation of high-quality, reliable tests.

                In summary, transitioning from Selenium to Playwright requires a solid understanding of both frameworks, the efficient use of the ray.run tool, and a grasp of asynchronous programming. With patience and practice, the transition can be smooth, unlocking Playwright's vast benefits.

                Migrating Tests from Selenium to Playwright

                Transitioning tests from Selenium to Playwright involves several crucial steps. Initially, it's essential to comprehend Playwright's documentation, API, and capabilities. Unlike Selenium, Playwright uses a websocket connection for browser control, resulting in faster, more efficient testing.

                An integral part of migration is the installation of Playwright and the selection of an appropriate adapter for your test framework. WebDriver initialization code in Selenium must be replaced with Playwright's browser engine initialization code.

                The way each platform handles interactive sessions differs significantly. While Selenium translates tests into JSON and sends them to the browser via a WebDriver, Playwright controls browsers directly for accelerated execution. Hence, it's necessary to update element interaction steps to align with Playwright’s asynchronous management.

                It’s critical to handle waits and delays differently during migration. Where Selenium waits for a specified time for an event, Playwright utilizes automatic waits tied to the browser's engine to conserve execution time.

                Updating assertions to conform to Playwright standards is also a crucial step. Post-alterations, incrementally conducted tests ensure functional components and prevent extensive problems due to building block failures.

                Throughout the migration process, version control is pivotal for quick rollbacks during significant failures. Also, project dependencies should be updated to accommodate Playwright.

                Migrated tests should be disabled and retained in Selenium as a failsafe, ensuring a straightforward return to the older system during unforeseen complications.

                Make the most of the enhanced parallel execution offered by Playwright, by parallelizing sequences that don't have dependent actions. This saves execution time.

                Transition challenges from Selenium to Playwright can occur, especially if the team has limited Node and TypeScript experience. Mitigate this by arranging comprehensive training sessions and following stellar software design patterns. With time, Playwright's speed, flexibility, and familiarity will enhance testing efficiency.

                Challenges and Solutions During Migration

                Transitioning from Selenium to Playwright may pose challenges, which can be managed through careful strategies. Potential issues include API differences between Selenium and Playwright, such as command handling, promise resolution, and async function approaches. There is also a difference in waiting strategy; Selenium uses explicit and implicit waits, while Playwright uses auto-waits, which simplifies test flow but can introduce complexities. Understanding Playwright's API is essential for adapting Selenium test scripts.

                The learning curve for team members unfamiliar with Playwright and JavaScript, the primary language of Playwright, may pose a difficulty. The language transition from Selenium's C# to Playwright's JavaScript could be challenging, especially for engineers with limited Node and TypeScript experience.

                Establishing a clear migration roadmap that includes staff training on Playwright and its difference with Selenium can mitigate these challenges. It is vital to note that Playwright controls browsers directly via a websocket connection, unlike Selenium that uses a webdriver. Identifying these technical differences is crucial for efficient test execution.

                Migration progress should be accurately tracked, and tests run incrementally to promptly handle arising issues. Proper version control practices are also crucial during migration.

                Following good software design patterns can aid those unfamiliar with Node/TypeScript. Writing codes and scripts independent of specific languages or frameworks lowers barriers. The migration process can become an efficient learning exercise and offer a more efficient testing framework despite the challenges.

                Migration from Selenium to Playwright

                Transitioning from Selenium to Playwright offers numerous benefits including faster testing speed, uniformity across multiple browsers, and automatic handling of waits and timeouts.

                The process involves becoming familiar with Playwright's API, installing Playwright and necessary browser drivers, and integrating it with your test framework using a Playwright adapter. The WebDriver initialization code is replaced with Playwright's and element interactions, waits, and assertions are updated. Running tests in parallel for speed and efficiency is recommended.

                Though challenges like API differences and different waiting strategies exist, they can be mitigated with training and a clear migration plan. Playwright, being faster and more powerful, makes high-quality test writing easier.

                The transition offers a more streamlined and powerful testing process, better support for modern web technologies, parallel cross-browser execution, and active community support. The process points towards a positive future in test automation.

                Thank you!
                Was this helpful?

                Now check your email!

                To complete the signup, click the confirmation link in your inbox.

                Subscribe to newsletter

                You will receive a weekly email with the latest posts and QA jobs.

                AboutQuestionsDiscord ForumBrowser ExtensionTagsQA Jobs

                Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email luc@ray.run.