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.
This post is part of my journey to learn Python. You can find the other parts of this series here. You find the code for this post in my PythonFriday repository on GitHub.
Installation
We can install Playwright with this pip command:
1 |
pip install pytest-playwright |
When this command succeeded, we can go on and install the browsers:
1 |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
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:
1 |
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:
1 |
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:
1 |
playwright codegen |
We only need to pick a supported format for Python and codegen switches its output to Python:
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.
3 thoughts on “Python Friday #152: Playwright for Python”