0
0
Selenium-pythonDebug / FixBeginner · 4 min read

How to Handle Cookies in Selenium Python: Fix and Best Practices

In Selenium Python, you handle cookies using the driver.get_cookies(), driver.add_cookie(), and driver.delete_cookie() methods. Always ensure you navigate to a domain before manipulating cookies, as trying to add or delete cookies without loading a page causes errors.
🔍

Why This Happens

When you try to add or delete cookies in Selenium Python without first opening a webpage, Selenium throws an error because cookies are tied to a specific domain. Without a loaded page, Selenium does not know which domain the cookie belongs to.

python
from selenium import webdriver

# Create driver
 driver = webdriver.Chrome()

# Attempt to add cookie before loading any page
 driver.add_cookie({'name': 'testcookie', 'value': '12345'})
Output
selenium.common.exceptions.InvalidCookieDomainException: You may only set cookies for the current domain
🔧

The Fix

To fix this, first navigate to the target website using driver.get(). Then you can safely add, get, or delete cookies because Selenium knows the domain context.

python
from selenium import webdriver

# Create driver
 driver = webdriver.Chrome()

# Open a page first
 driver.get('https://example.com')

# Add a cookie
 driver.add_cookie({'name': 'testcookie', 'value': '12345'})

# Get all cookies
 cookies = driver.get_cookies()
 print(cookies)

# Delete a cookie
 driver.delete_cookie('testcookie')
Output
[{'name': 'testcookie', 'value': '12345', 'domain': 'example.com', 'path': '/', 'secure': False, 'httpOnly': False}]
🛡️

Prevention

Always load a webpage before manipulating cookies to avoid domain errors. Use descriptive cookie names and values. Clear cookies when tests finish to avoid state leaks. Use Selenium's cookie methods consistently and check cookie presence before deletion.

⚠️

Related Errors

Common related errors include InvalidCookieDomainException when adding cookies without a domain, and NoSuchCookieException when deleting a cookie that does not exist. Always verify the domain and cookie existence before operations.

Key Takeaways

Always open a webpage with driver.get() before adding or deleting cookies.
Use driver.get_cookies() to retrieve all cookies for the current domain.
Clear cookies after tests to maintain a clean state.
Check cookie existence before deleting to avoid errors.
Cookie operations are domain-specific; Selenium requires a loaded page.