Playwright >> Save authentication state and Login atuomatically
Table of Contents
In the previous article, we introduced the basic usage of Playwright. In this article, we will talk about some advanced usage like auto-login and save authentication states like cookies or tokens.
Recording login steps
Let’s login to https://www.pinterest.com/ for example.
We enter the command below to record the code.
playwright codegen https://www.pinterest.com/
If you haven’t installed Playwright and its dependencies, you can read the previous article that introduces the basic usage of Playwright.
Playwright » Basic Usage
https://thats-it-code.com/playwright/playwright__basic-usage/
When the command is executed, the chromium browser will be opened and go to Pinterest.com site. To log into Pinterest, click log in button.
After clicking log in button, the login dialog will pop up.
Let’s fill in the Email and password fields and click Log in button.
Before closing the browser, open the window for code recording and click the copy button to copy the code and paste it to IDE(Integrated Development Environment).
You can read the articles below to learn how to build a programming environment in your PC.
Let’s Create a Programming Environment
https://thats-it-code.com/programming/lets-create-a-programming-environment/ How to Create Python Virtual Environment
https://thats-it-code.com/programming/how-to-create-python-virtual-environment/
To check if we can log into Pinterest.com or not, let’s execute the code with debug mode.
The execution will be stopped at the breakpoint and we switch to the browser window, we will find that we have logged in to pinterest.com successfully.
And stop the debugging.
Save authentication state
Next, let’s save the authentication information (cookies or token included) to the local JSON file. To achieve this we should add a line of code before closing context and browser.
# Save storage state into the file. ← Add this line
context.storage_state(path="data/state.json") # ← Add this line
# ---------------------
context.close()
browser.close()
The whole code will be as below.
from playwright.sync_api import Playwright, sync_playwright
def run(playwright: Playwright) -> None:
browser = playwright.chromium.launch(headless=False)
context = browser.new_context()
# Open new page
page = context.new_page()
# Go to https://www.pinterest.com/
page.goto("https://www.pinterest.com/")
# Click button:has-text("Log in")
page.click("button:has-text(\"Log in\")")
# Click [placeholder="Email"]
page.click("[placeholder=\"Email\"]")
# Fill [placeholder="Email"]
page.fill("[placeholder=\"Email\"]", "{Your Email Address}")
# Click [placeholder="Password"]
page.click("[placeholder=\"Password\"]")
# Fill [placeholder="Password"]
page.fill("[placeholder=\"Password\"]", "{Your password}")
# Click [data-test-id="registerFormSubmitButton"] [aria-label=""]
# with page.expect_navigation(url="https://www.pinterest.com/"):
with page.expect_navigation():
page.click("[data-test-id=\"registerFormSubmitButton\"] [aria-label=\"\"]")
# Save storage state into the file.
context.storage_state(path="data/state.json")
# ---------------------
context.close()
browser.close()
with sync_playwright() as playwright:
run(playwright)
After adding the code for saving authentication information, let’s execute the whole code again. We will find that the JSON file will be generated in the data folder.
Reuse authentication state to log in automatically
If we don’t want to log in every time, we can use this authentication information file by modifying the code below.
# context = browser.new_context()
# ↓↓↓
# Create a new context with the saved storage state.
context = browser.new_context(storage_state="data/state.json")
And delete the lines for logging in steps.
The final code will be as below.
from playwright.sync_api import Playwright, sync_playwright
def run(playwright: Playwright) -> None:
browser = playwright.chromium.launch(headless=False)
# Create a new context with the saved storage state.
context = browser.new_context(storage_state="data/state.json")
# Open new page
page = context.new_page()
# Go to https://www.pinterest.com/
page.goto("https://www.pinterest.com/")
# ---------------------
context.close()
browser.close()
with sync_playwright() as playwright:
run(playwright)
Next, let’s execute the code with debugging mode and stop the execution at the point of closing the context.
And switch the browser, we will find that we logged in Pinterest.com successfully without entering Email and password.
Conclusion
In this article, we generated the code for logging in Pinterest.com using the code generation command.
And add the code for saving authentication information.
Finally, we use the generated authentication to log into the website without entering Email and password.