Understanding Browser Contexts and Session Management in Playwright
This article explains Playwright's browser contexts and session management, describing how each context isolates cookies and storage, how to create and control pages with methods like newContext(), newPage(), pages(), bringToFront(), and close(), and provides a complete code example demonstrating multiple contexts for login and data scraping.
When using Playwright, understanding browser contexts and session management is essential.
1. Browser Context
A browser context is an isolated environment that contains a set of pages and shared browser state; each context has its own cookies, cache, and other data, effectively acting as a separate browser instance.
In Playwright you create a new context with browser.newContext(). By default a browser instance has a default context, but you can create multiple independent contexts within the same instance.
2. Session Management
Session management involves opening, operating, and closing pages across one or more browser contexts. Playwright provides methods such as browser.newPage() to create a page, browser.pages() to list all pages, page.bringToFront() to focus a page, and page.close() to close it.
Additional methods include browser.newContext() for creating new contexts and browser.close() for shutting down the browser instance. Using multiple contexts and pages allows isolation of different sessions, such as one context for login and another for data scraping.
Code Example
from playwright import sync_playwright
def perform_login(page):
# Execute login actions
# ...
def scrape_data(page):
# Scrape data
# ...
with sync_playwright() as playwright:
# Create first browser context and perform login
browser1 = playwright.chromium.launch()
context1 = browser1.newContext()
page1 = context1.newPage()
page1.goto('https://example.com/login')
perform_login(page1)
# Create second browser context and scrape data
browser2 = playwright.chromium.launch()
context2 = browser2.newContext()
page2 = context2.newPage()
page2.goto('https://example.com/data')
scrape_data(page2)
# Close browsers
browser1.close()
browser2.close()The example demonstrates creating two independent browser instances, each with its own context and page, performing login in the first and data extraction in the second, and finally closing both browsers.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
