Python Friday #156: Connect Playwright to BrowserStack and Selenium Grid

If you must run Playwright on a specific browser, you will find a service like BrowserStack a great help. Let’s look how we can connect Playwright to BrowserStack and Selenium Grid.

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.

 

Prerequisites for BrowserStack

For BrowserStack we need an account that can run code on the Automate feature. If you do not already have an account, you can create one for free and test BrowserStack.

 

Connect to BrowserStack

As with .Net you can get the example for Python directly from BrowserStack. I only shortened a few lines and use the .env file for the credentials.

Since BrowserStack offers such a large variety of browsers and operating systems, we need to specify what combination we want to use. We can define the desired capabilities in the desired_cap dictionary. That is also the place where we need to set the credentials for BrowserStack – otherwise we get a strange exception.

If we run the application, we get a video and a detailed list of the activities on BrowserStack:

Our code run successful on BrowserStack

Marking the state of the test in BrowserStack did not work with Playwright 1.27 and 1.28. I hope this will work with newer versions.

 

Prerequisites for Selenium Grid

We need to create a dynamic Selenium Grid on Docker. You find both necessary files to configure the grid in my C# post Run Playwright on Selenium Grid.

When you saved the files, you can run the grid with this command:

 

Run your code in Selenium Grid

We use this little application to test Selenium Grid:

When we run this application, it should give us an output like this:

YOUR WEB BROWSER IS:
Chrome 108 on Windows 11

We can switch to Selenium Grid by setting the environment variable SELENIUM_REMOTE_URL to our grid:

If we now run the application again, it uses Selenium Grid and produces an output like this one:

YOUR WEB BROWSER IS:
Chrome 106 on Linux

You can set the environment variable inside your code, but it is not necessary.

 

Next

This concludes the Python specific posts on Playwright. As you could see over the last few weeks, there is much similarity between C# and Python when it comes to Playwright. Usually, the code is a little bit simpler on Python, but there are no meaningful differences.

Next Tuesday I conclude my posts on Playwright with a recapitulation of the covered topics and answer the question if you should switch to Playwright.

Leave a Comment

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