Python Friday #153: Automate Browsers With Playwright

Last week we got Playwright up and running in Python. In this post we build on that and start to automate our browser.

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.

 

Navigate to the web page

Before we can start looking for elements, we need to open the web page we are interested in. We can call the goto() method on the page object (from a Playwright fixture for pytest):

If you run Playwright outside of a test class, you can use this code from the codegen template as your starting point:

 

Get the title of a page

We can get the title of the current page with the title() method:

 

Locators

Playwright uses locators to find the elements on a web page. There are a few types that we can choose from, but the documentation recommends that we prioritize role locators to locate elements (they are closer to the way users and assistive technology access the page). However, codegen for Python still uses a lot of the other locators and so will we for the time being.

If we want to search an element by its ID, we can add a # as a prefix or use the id= shorthand in the locator() method:

These examples only scratch the surface of locators. The more you work with Playwright, the simpler it gets to use a fitting combination of the various locators. Start with the examples from above and then add more if you need a more precise selector.

 

Fill input forms

If we get an element that accepts a text input, we can write to it with the fill() method:

 

Click buttons

We can click buttons with the click() method:

If you selected an element in a form, you can often use press(“Enter”) to simulate the user hitting the enter key on the keyboard:

 

Read values from elements

The methods inner_text() and text_content() allow us to access the text of an element through the locator:

If the element contains other elements with text and we want everything in one go, we can use the method all_inner_texts() to get the content as a list of strings:

 

Close the browser

If you run Playwright outside of pytest, you should close the context and the browser at the end of your application:

 

Next

With the basics covered, you should be able to automate the Playwright browser for your first tests. Next week we will look at ways to narrow down the reasons why our Playwright automation no longer works.

1 thought on “Python Friday #153: Automate Browsers With Playwright”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.