Introduction
Adding Cookies in Selenium allows you to insert new cookies into the current browser session. Cookies store important information such as user sessions, authentication tokens, preferences, and other website-specific data.
Using Selenium’s add_cookie() method, automation testers can create cookies manually without interacting with the application’s user interface. This is especially useful for bypassing login pages, restoring user sessions, testing personalized features, and simulating specific browser states.
One important requirement is that Selenium must first navigate to the target website before adding cookies. Cookies can only be added to the currently opened domain.
In this tutorial, you will learn what adding cookies means, why it is used, its syntax, practical examples, real-world applications, common mistakes, best practices, and frequently asked interview questions.
What is Adding Cookies?
Adding Cookies is the process of inserting a new cookie into the browser using Selenium.
Once added, the website treats the cookie as if it had been created naturally during browsing.
Cookies can contain information such as:
Login session IDs
User preferences
Language settings
Authentication tokens
Shopping cart information
Why Do We Add Cookies?
Adding cookies is commonly used to:
Skip login pages.
Restore authenticated sessions.
Simulate returning users.
Test personalized website behavior.
Reduce repetitive login steps.
Speed up automation execution.
Syntax
Add a Cookie
driver.add_cookie({"name": "cookie_name", "value": "cookie_value"})
Read the Cookie
driver.get_cookie("cookie_name")
Practical Example
The following example demonstrates how to add a cookie to the current browser session.
The automation script opens the Selenium practice website, adds a custom cookie named test_cookie, retrieves it, and verifies that its value matches the expected value.
from selenium import webdriver
# Topic: 9. Managing Browser Sessions - Adding Cookies
# Practice site: https://the-internet.herokuapp.com/
#
# add_cookie() inserts a cookie into the current browser session. You must
# navigate to the target domain before adding a cookie.
def test_add_cookie():
driver = webdriver.Chrome()
try:
driver.get("https://the-internet.herokuapp.com/")
driver.add_cookie(
{
"name": "test_cookie",
"value": "selenium_python",
}
)
cookie = driver.get_cookie("test_cookie")
assert cookie["value"] == "selenium_python"
finally:
driver.quit()
Output
Chrome launched successfully.
Website opened successfully.
Cookie added successfully.
Retrieved Cookie:
Name: test_cookie
Value: selenium_python
Assertion Passed.
Test Executed Successfully.
Understanding the Code
Import WebDriver
from selenium import webdriver
Imports the Selenium WebDriver module.
Launch Chrome
driver = webdriver.Chrome()
Starts a new Chrome browser session.
Open the Website
driver.get("https://the-internet.herokuapp.com/")
Navigates to the target website.
Important: Selenium must open the website before adding cookies because cookies belong to a specific domain.
Add a Cookie
driver.add_cookie(
{
"name": "test_cookie",
"value": "selenium_python",
}
)
Creates a new cookie named test_cookie with the value selenium_python.
Retrieve the Cookie
cookie = driver.get_cookie("test_cookie")
Retrieves the cookie that was just added.
Verify the Cookie Value
assert cookie["value"] == "selenium_python"
Confirms that the cookie was successfully added and contains the expected value.
Close the Browser
driver.quit()
Closes all browser windows and ends the WebDriver session.
Browser Execution Flow
Launch Chrome
│
▼
Open Website
│
▼
Add Cookie
│
▼
Browser Stores Cookie
│
▼
Retrieve Cookie
│
▼
Verify Cookie Value
│
▼
Assertion Passes
│
▼
Close Browser
Cookie Dictionary Structure
A cookie is added using a Python dictionary.
Example:
{
"name": "test_cookie",
"value": "selenium_python"
}
Common cookie properties include:
| Property | Description |
|---|---|
name | Cookie name |
value | Cookie value |
domain | Website domain (optional) |
path | Cookie path (optional) |
expiry | Expiration time (optional) |
secure | HTTPS only (optional) |
httpOnly | Prevents JavaScript access (optional) |
Automation Testing Example
Suppose an e-commerce application requires users to log in before accessing the Orders page.
Instead of logging in before every test:
Selenium opens the website.
Adds a previously saved authentication cookie.
Refreshes the page.
The user is automatically recognized as logged in.
This significantly reduces test execution time.
Real-World Example
Consider a CRM application where testers execute hundreds of regression tests daily.
The automation framework:
Logs in once.
Stores the session cookie.
Reuses the same cookie for multiple test cases.
Skips repeated login operations.
This improves automation speed and reduces unnecessary server requests.
Common Mistakes Beginners Make
Adding Cookies Before Opening the Website
Incorrect
driver = webdriver.Chrome()
driver.add_cookie(
{
"name": "test",
"value": "123"
}
)
This throws an error because no domain has been loaded.
Correct
driver.get("https://the-internet.herokuapp.com/")
driver.add_cookie(
{
"name": "test",
"value": "123"
}
)
Using Duplicate Cookie Names
Adding another cookie with the same name may overwrite the existing one.
Use unique names when appropriate.
Forgetting to Verify the Cookie
Always retrieve the cookie after adding it to ensure it was stored successfully.
Best Practices
Open the target website before adding cookies.
Use cookies to simplify authentication-related tests.
Verify cookies after adding them.
Store reusable authentication cookies securely.
Remove unnecessary cookies after test execution.
Always close the browser using
driver.quit().
Conclusion
Adding Cookies allows Selenium to insert cookies directly into the browser, making it easier to simulate authenticated sessions, personalize browser behavior, and speed up automation execution. Since cookies belong to a specific domain, the browser must first navigate to the target website before cookies can be added.
Using add_cookie() is a powerful technique for managing browser sessions efficiently in Selenium automation frameworks.
Frequently Asked Questions (FAQs)
What is add_cookie() in Selenium?
add_cookie() inserts a new cookie into the current browser session.
How do I add a cookie?
driver.add_cookie(
{
"name": "test_cookie",
"value": "selenium_python"
}
)
Can I add cookies before opening a website?
No.
The browser must first navigate to the target domain before adding cookies.
How do I retrieve a cookie?
driver.get_cookie("test_cookie")
Why are cookies added during automation?
Cookies are added to restore sessions, bypass login pages, simulate authenticated users, and speed up automation execution.
Key Takeaways
add_cookie()inserts a new cookie into the current browser session.Open the target website before adding cookies.
Cookies are added using a Python dictionary containing at least a name and value.
Use
get_cookie()to verify that the cookie was added successfully.Adding cookies helps bypass login pages and restore user sessions.
Cookie management improves automation efficiency and reduces repetitive login operations.
Always close the browser using
driver.quit().Adding Cookies is an important Selenium browser session management feature and a commonly asked interview topic.
