Caching User Credentials
If you have an automation that requires logging into a site, you can save time by securely caching and passing your credentials.
Overview
This guide shows how to avoid logging into the website multiple times by caching user credentials with AgentQL.
Cache user credentials
After logging into a site, you need to save all relevant authentication cookies and local storage with the storage_state()
method.
Here's an example of saving the current browser session to a local file called session.json
.
Here is the complete script that saves your current session with the website into a local file for future use authenticating sessions:
Load user credentials
To load the session that was saved to a local file, start a new browser context with the path of the session file from cache user credentials as an argument with the new_context()
method.
browser.new_context(storage_state="session.json")
Here is a complete script that loads the saved session:
import agentql
from playwright.sync_api import sync_playwright
with sync_playwright() as playwright, playwright.chromium.launch(headless=False) as browser:
# Load the saved signed-in session by creating a new browser context with the saved session
context = browser.new_context(storage_state="session.json")
page = agentql.wrap(context.new_page())
page.goto(URL)
page.wait_for_page_ready_state()
# Used only for demo purposes. It allows you to see the effect of the script.
page.wait_for_timeout(10000)
Conclusion
Now that you understand how to save a session and load it in future sessions, you can enhance your workflows by caching and passing authetication credentials.