Skip to content

#152: Playwright for Python

Over the last few weeks, I experimented with Playwright and wrote a few posts on how to work with it from C#. Because I got so many comments about Playwright whenever I blog about Selenium, I go for a slightly shorter set of posts that cover Playwright for Python users. The obstacles I run into in C# may happen to you in Python too.

Installation

We can install Playwright with this pip command:

pip install pytest-playwright

When this command succeeded, we can go on and install the browsers:

playwright install

In Python we do not need to go to an output folder and run a PowerShell script as we do in .Net. Here we can call playwright directly and it works.

Create a test

For our first test we can follow along the official documentation for Playwright and Python and create this test for pytest:

import re
from playwright.sync_api import Page, expect


def test_first_steps(page: Page):
    page.goto("https://playwright.dev/")

    # Expect a title "to contain" a substring.
    expect(page).to_have_title(re.compile("Playwright"))

    # create a locator
    get_started = page.get_by_role("link", name="Get started")

    # Expect an attribute "to be strictly equal" to the value.
    expect(get_started).to_have_attribute("href", "/docs/intro")

    # Click the get started link.
    get_started.click()

    # Expects the URL to contain intro.
    expect(page).to_have_url(re.compile(".*intro"))

This test uses the Page fixture that comes with Playwright. It creates the browser for us and let us interact directly with the (web) page.

Run the test

We can run the test with this command:

pytest

This runs our test in the headless mode. If we want to see what is going on, we need to use the –headed option:

pytest --headed

Record tests

The test recorder codegen works the same way as it does for .Net / C#. We can start it with this command:

playwright codegen

We only need to pick a supported format for Python and codegen switches its output to Python:

Choose Python as the output format to get Python code from codegen

Next

The installation of Playwright for Python is similar to .Net. It uses pip instead of NuGet, but otherwise it works the same way. The same is true for the test recorder codegen, where we only need to change the output format. Next week we look at the methods we need to automate a browser with Playwright in Python.