Working with cookies and sessions is an essential skill for developers dealing with web automation and testing. Playwright, a powerful library, provides developers the tools to automate web browsers using Python, making it efficient to interact and manipulate cookies and sessions during automated testing processes.
Getting Started with Playwright
Before diving into cookies and sessions, ensure you have Playwright installed. You can install it via pip:
pip install playwright
Don't forget to install browser binaries required by Playwright:
python -m playwright install
Managing Cookies
Cookies are small data files used by websites to store stateful information about users. Managing cookies in Playwright allows you to simulate user sessions, remember information between pages, and maintain login states.
Set a Cookie
Setting a cookie is a straightforward process in Playwright. First, launch a browser and create a new page:
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch()
page = browser.new_page()
page.goto('https://example.com')
page.context.add_cookies([
{
'name': 'username',
'value': 'john_doe',
'domain': 'example.com',
'path': '/',
'expires': -1 # -1 means no expiration
}
])
browser.close()
Get a Cookie
To retrieve cookies, use the following method:
cookies = page.context.cookies()
print(cookies)
This method returns all cookies, which you can then filter to access specific cookies by their attributes like name or domain.
Delete a Cookie
If you need to clear specific cookies, you can do so using the context’s clear_cookies method:
page.context.clear_cookies()
Working with Sessions
Sessions in web applications help maintain continuity and manage user states. Playwright provides features to manage sessions through storing and restoring authentication state.
Preserving Session State
To preserve session states such as login information across multiple test scenarios, use the following approach:
page.context.storage_state(path='session.json')
This command stores the current authenticated session in a file named session.json.
Using Stored Session State
When you want to reuse a session state, simply load it when creating a new browser context:
context = browser.new_context(storage_state='session.json')
page = context.new_page()
This will open a new page where the user is already logged into their session.
Example: Automated Login Management
Let's integrate the above concepts into a complete example where we automate a login and save the session:
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch(headless=False)
context = browser.new_context()
page = context.new_page()
page.goto('https://example.com/login')
# Perform login
page.fill('input[name="username"]', 'my_user')
page.fill('input[name="password"]', 'my_password')
page.click('text="Login"')
# Saving the session state for future use
context.storage_state(path='session.json')
# Closing browser
browser.close()
Running this script will log into the site and save the session state, which can later be used to rerun tests without needing to log in again.
Conclusion
Playwright makes managing cookies and sessions straightforward, providing developers with powerful tools to simulate real-world user scenarios. By efficiently managing cookies and sessions, you can create reliable and comprehensive automation scripts that improve the quality of your web applications.