Introduction
A Browser Session represents the period during which Selenium WebDriver controls a browser instance. Throughout a browser session, Selenium maintains the browser’s state, including open tabs, cookies, authentication, local storage, and session storage.
One of the most important aspects of browser sessions is session cookies. After a successful login, most web applications create a session cookie that keeps the user authenticated while navigating between pages or refreshing the browser.
Selenium allows automation testers to retrieve, reuse, and manage these session cookies, making it possible to validate login persistence, reduce repetitive logins, and improve automation efficiency.
In this tutorial, you will learn what browser sessions are, why session management is important, how Selenium manages browser sessions, practical examples, real-world applications, common mistakes, best practices, and frequently asked interview questions.
What is a Browser Session?
A browser session begins when Selenium launches a browser and ends when the browser is closed using driver.quit().
During a session, Selenium maintains information such as:
Browser cookies
Login state
Open tabs and windows
Browser history
Local storage
Session storage
If the session cookie remains valid, the user stays logged in even after navigating to different pages or refreshing the browser.
Why Do We Manage Browser Sessions?
Managing browser sessions helps automation testers to:
Maintain login state across pages.
Avoid repeated logins.
Verify session persistence.
Test authenticated areas of an application.
Validate session timeout functionality.
Improve automation execution speed.
Browser Session Lifecycle
Launch Browser
│
▼
Open Website
│
▼
Login Successfully
│
▼
Server Creates Session Cookie
│
▼
Navigate Between Pages
│
▼
Refresh Browser
│
▼
User Remains Logged In
│
▼
Close Browser
│
▼
Session Ends
Practical Example
The following example demonstrates how Selenium manages a browser session using session cookies.
The automation script opens the login page, performs a successful login, retrieves the session cookies, refreshes the browser, and verifies that the user remains logged in because the session cookie is still valid.
from selenium import webdriver
from selenium.webdriver.common.by import By
# Topic: 9. Managing Browser Sessions - Managing Browser Sessions
# Practice site: https://the-internet.herokuapp.com/login
#
# Session cookies persist login state across page loads. This example logs in,
# stores the session cookie, and verifies it survives a page refresh.
def test_manage_browser_session_with_cookies():
driver = webdriver.Chrome()
try:
driver.get("https://the-internet.herokuapp.com/login")
driver.find_element(By.ID, "username").send_keys("tomsmith")
driver.find_element(By.ID, "password").send_keys("SuperSecretPassword!")
driver.find_element(By.CSS_SELECTOR, "button[type='submit']").click()
assert "You logged into a secure area!" in driver.find_element(
By.CSS_SELECTOR,
".flash"
).text
session_cookies = driver.get_cookies()
driver.refresh()
assert driver.current_url.endswith("/secure")
assert len(session_cookies) > 0
finally:
driver.quit()
Output
Chrome launched successfully.
Login page opened.
Username entered.
Password entered.
Login successful.
Session cookie created.
Retrieved session cookies.
Browser refreshed.
User remained logged in.
Assertion Passed.
Test Executed Successfully.
Understanding the Code
Import Required Modules
from selenium import webdriver
from selenium.webdriver.common.by import By
Imports Selenium WebDriver and the By locator strategy.
Launch Chrome
driver = webdriver.Chrome()
Starts a new browser session.
Open the Login Page
driver.get("https://the-internet.herokuapp.com/login")
Navigates to the login page.
Enter Username
driver.find_element(
By.ID,
"username"
).send_keys("tomsmith")
Enters the valid username.
Enter Password
driver.find_element(
By.ID,
"password"
).send_keys("SuperSecretPassword!")
Enters the valid password.
Click Login
driver.find_element(
By.CSS_SELECTOR,
"button[type='submit']"
).click()
Submits the login form.
Verify Login Success
assert "You logged into a secure area!" in driver.find_element(
By.CSS_SELECTOR,
".flash"
).text
Confirms that the login was successful.
Retrieve Session Cookies
session_cookies = driver.get_cookies()
Retrieves all cookies created after login, including the authentication session cookie.
Refresh the Browser
driver.refresh()
Reloads the current page.
Since the session cookie still exists, the user remains logged in.
Verify Session Persistence
assert driver.current_url.endswith("/secure")
assert len(session_cookies) > 0
Verifies that:
The user is still on the secure page.
Session cookies are available.
Close the Browser
driver.quit()
Ends the browser session.
Browser Execution Flow
Launch Chrome
│
▼
Open Login Page
│
▼
Enter Credentials
│
▼
Login Successfully
│
▼
Server Creates Session Cookie
│
▼
Retrieve Cookies
│
▼
Refresh Browser
│
▼
User Remains Logged In
│
▼
Assertions Pass
│
▼
Close Browser
Browser Session Components
| Component | Purpose |
|---|---|
| Cookies | Maintain login sessions and preferences |
| Local Storage | Stores persistent browser data |
| Session Storage | Stores temporary browser data |
| Window Handles | Tracks open tabs and windows |
| Browser History | Stores visited pages during the session |
Automation Testing Example
Suppose your company is testing an employee portal.
Instead of logging in before every test case:
Selenium logs in once.
Retrieves the authentication cookies.
Navigates across multiple secure pages.
Refreshes the browser.
Confirms the user remains authenticated.
This significantly reduces execution time.
Real-World Example
Consider an internet banking application.
After successful login:
The server creates a secure session cookie.
Selenium retrieves the cookie.
The browser refreshes several pages.
The application continues recognizing the user.
Only after logout or session timeout does access end.
This validates that session management is working correctly.
Common Mistakes Beginners Make
Assuming Refresh Ends the Session
Refreshing the browser does not end the browser session.
If the session cookie remains valid, the user stays logged in.
Confusing Browser Session with Browser Window
Closing a single browser tab using:
driver.close()
does not necessarily end the WebDriver session.
The session ends only when:
driver.quit()
is executed.
Forgetting to Verify Session Persistence
Always verify that:
Login remains active.
Session cookies exist.
The user stays on authenticated pages after refresh.
Best Practices
Verify session cookies after login.
Reuse browser sessions when appropriate.
Test session persistence after page refresh.
Validate logout by deleting session cookies.
Avoid unnecessary repeated logins during automation.
Always terminate the session using
driver.quit().
Conclusion
Managing Browser Sessions is an essential part of Selenium automation. Browser sessions preserve cookies, authentication state, browser history, and other session-related information throughout test execution. Proper session management allows automation engineers to verify login persistence, improve test performance, and create reliable end-to-end automation frameworks.
Understanding browser sessions and session cookies is a fundamental Selenium skill and is frequently used in real-world automation projects.
Frequently Asked Questions (FAQs)
What is a browser session in Selenium?
A browser session is the lifetime of a WebDriver-controlled browser, starting when the browser launches and ending when driver.quit() is called.
How does Selenium maintain login sessions?
Selenium maintains login sessions using the browser’s session cookies created after successful authentication.
Does refreshing the browser end the session?
No.
Refreshing the page reloads the current webpage while preserving valid session cookies.
How can I retrieve session cookies?
driver.get_cookies()
How do I end a browser session?
driver.quit()
Key Takeaways
A browser session starts when Selenium launches the browser and ends when
driver.quit()is called.Session cookies keep users logged in across page navigations and browser refreshes.
Selenium can retrieve session cookies using
get_cookies().Refreshing the browser does not terminate an active session.
Browser sessions improve automation efficiency by avoiding repeated logins.
Session management is essential for testing authentication, secure pages, and user workflows.
Always close the browser using
driver.quit()after test execution.Managing Browser Sessions is a fundamental Selenium concept and a frequently asked interview topic.
