Automate Browsers With Playwright

After we got Playwright up and running in the last post, we can now take a closer look on how we can automate a web browser with Playwright.

 

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 GotoAsync() method on our Page instance:

The Page object comes from the class PageTest which we inherited from in our test class. If you run Playwright outside of a test class, you can use this code to get the Page object:

 

Get the title of a page

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

 

Selectors & locators

Playwright uses selectors and locators to interact with elements on a web page. The selectors are the strings we use to define the elements we want, while the locators are the objects on which we call the methods to perform the desired actions (e.g., Locator.ClickAsync() to click a button).

Playwright offers various ways to define your selectors. I will cover only the most basic selectors to get you started. When you need more, check the official documentation to find a better match. And while you are there, read the section on best practices – following this advice will make your tests more robust.

Text selectors help us to find elements using the text they display. If we have an element with the text “Log in”, we can create a selector like this:

CSS selectors operate on the shadow DOM. We can use selectors as we know from CSS and use things like the nth-matcher to find the last button on a page:

There is no cut-and-dry separation between these selectors. We can combine a text selector with a CSS selector to get exactly the element we are looking for:

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

These examples only scratch the surface of selectors. The more you work with Playwright, the simpler it gets to use the combination of text and CSS selectors. 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 FillAsync() method:

 

Click buttons

We can click buttons with the ClickAsync() method:

 

Read values from elements

The methods InnerTextAsync() and TextContentAsync() 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 AllInnerTextsAsync() to get the content as a list of strings:

 

Next

With the basics covered in this post you should be able to automate the Playwright browser for your first tests. Next week we look at Codegen and how we can use it to create selectors for us.

1 thought on “Automate Browsers With Playwright”

Leave a Comment

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