There are multiple ways that authentication is implemented on a website, most commonly through a login form that requires users' credentials to be input. However, some sites may implement Basic HTTP Authentication where credentials are requested by the server and are not handled by an interactive form in the browser.
Let’s start with writing a Python script that uses Playwright to visit a website that implements basic HTTP authentication. See Getting started with Playwright in Python for an introduction to the basics if required.
=
=
=
Run the script and open the screenshot that this script captured, you will see something like this, stating that you are not authorised.
This page implements basic HTTP authentication, which requires a username and password. These are both admin
for this particular site. There are several ways to handle this with our Playwright script.
Deprecated method using URL
The first method is to pass the credentials in the URL. This should work but is now deprecated and not the recommended solution. We can tweak our script to include admin:admin@
at the beginning of our URL.
=
=
=
When we run this script now, we should see that the screenshot now shows a page confirming that we have provided the required credentials and accessed the webpage.
Recommended method using Playwright browser context
Playwright provides us with a more modern solution, where we can pass these credentials into the browser context that we create in our script. To do this we can use the browser.new_context()
method and pass in the username and password in a dictionary for the http_credentials
argument. We can then create the page object from this browser context.
=
=
=
Checking the screenshot you will see that we can now successfully handle the authentication and access the website.
Back to top^