Reading and Writing Cookies in Selenium Python
When automating web applications using Selenium in Python, dealing with cookies is often essential. Cookies store session data, user preferences, authentication tokens, and other information that can help in navigating a site without repeating the same steps every time—like logging in. Understanding how to read and write cookies in Selenium gives you control over the browser session and enables smarter automation.
In this blog post, we’ll cover how to handle cookies in Selenium Python—reading, adding, saving, and loading cookies—with practical examples and tips.
What Are Cookies?
Cookies are small text files stored in the browser by websites. They typically hold data such as:
- Session IDs (for keeping users logged in)
- Preferences (e.g., language, theme)
- Tracking data (analytics or ad targeting)
In automation, cookies allow you to maintain session state or simulate specific scenarios without redoing every step.
Setting Up Selenium in Python
To get started, install Selenium (if not already installed):
bash
pip install selenium
You’ll also need a WebDriver. Here’s how to initialize one with Chrome:
python
from selenium import webdriver
driver = webdriver.Chrome()
driver.get("https://example.com")
Reading Cookies
Once you're on a page, reading cookies is simple:
python
# Get all cookies
cookies = driver.get_cookies()
for cookie in cookies:
print(f"{cookie['name']} = {cookie['value']}")
# Get a specific cookie by name
session_cookie = driver.get_cookie("session_id")
print(session_cookie)
This is useful for checking whether authentication or preferences are set properly.
Writing (Adding) Cookies
You can add cookies manually to simulate a logged-in session or a specific user state.
python
Copy
Edit
# Must navigate to domain before setting cookies
driver.get("https://example.com")
# Add a cookie
driver.add_cookie({
"name": "session_id",
"value": "123456abcdef"
})
After adding cookies, refresh the page to see them in action:
python
Copy
Edit
driver.refresh()
Note: Cookies must match the domain currently open in the browser. You can't add cookies for a domain the driver hasn’t visited.
Saving and Loading Cookies (Persistent Sessions)
Save Cookies to File
python
Copy
Edit
import json
cookies = driver.get_cookies()
with open("cookies.json", "w") as f:
json.dump(cookies, f)
Load Cookies from File
python
Copy
Edit
with open("cookies.json", "r") as f:
saved_cookies = json.load(f)
driver.get("https://example.com")
for cookie in saved_cookies:
driver.add_cookie(cookie)
driver.refresh()
This allows you to log in once manually, save the cookies, and reuse them for subsequent test runs—saving time and avoiding repetitive login automation.
Deleting Cookies
You can also delete cookies if needed:
python
Copy
Edit
# Delete a specific cookie
driver.delete_cookie("session_id")
# Delete all cookies
driver.delete_all_cookies()
Useful for cleanup or testing how your app behaves without session data.
Best Practices
- Always navigate to the target domain before manipulating cookies.
- Use cookies to bypass logins only when secure and appropriate, especially in test environments.
- Clear cookies when tests are complete to avoid conflicts.
- Validate cookie properties such as expiry and path when debugging.
Conclusion
Reading and writing cookies in Selenium Python is a powerful technique that enhances your automation scripts by giving you direct control over browser session state. Whether you’re trying to bypass repetitive login flows, test personalized user experiences, or simulate session expiry, managing cookies can make your test suite faster, smarter, and more robust. Start small—read, add, and delete cookies—and build up to managing full session persistence for complex test scenarios.
Learn Selenium with Python Training Course
Read More: Automating File Uploads with Selenium Python
Visit Quality Thought Training Institute in Hyderabad
Get Direction
Comments
Post a Comment