How to Add Cookie in Selenium: Syntax and Example
To add a cookie in Selenium, use the
add_cookie() method on the WebDriver instance with a dictionary containing cookie details like name and value. Make sure to add cookies only after navigating to a domain, as cookies are domain-specific.Syntax
The add_cookie() method requires a dictionary with at least name and value keys. Optional keys include path, domain, secure, and expiry.
- name: The cookie's name (string).
- value: The cookie's value (string).
- path: The path for the cookie (string, optional).
- domain: The domain for the cookie (string, optional).
- secure: Whether the cookie is secure (boolean, optional).
- expiry: Expiration time as UNIX timestamp (int, optional).
Cookies must be added after navigating to a page on the target domain.
python
driver.add_cookie({'name': 'cookie_name', 'value': 'cookie_value'})Example
This example shows how to open a website, add a cookie, and verify it was added successfully.
python
from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.chrome.options import Options options = Options() options.add_argument('--headless') service = Service() driver = webdriver.Chrome(service=service, options=options) try: driver.get('https://www.example.com') cookie = {'name': 'test_cookie', 'value': '12345'} driver.add_cookie(cookie) retrieved_cookie = driver.get_cookie('test_cookie') assert retrieved_cookie is not None assert retrieved_cookie['value'] == '12345' print('Cookie added and verified successfully.') finally: driver.quit()
Output
Cookie added and verified successfully.
Common Pitfalls
- Trying to add a cookie before navigating to any page causes an error because Selenium needs a domain context.
- Not including required keys like
nameorvaluein the cookie dictionary will raise exceptions. - Adding cookies with incorrect domain or path may cause them to be ignored.
Always navigate to the target domain first, then add cookies.
python
from selenium import webdriver driver = webdriver.Chrome() # Wrong: Adding cookie before loading a page try: driver.add_cookie({'name': 'wrong', 'value': 'fail'}) except Exception as e: print(f'Error: {e}') # Right: Navigate first, then add cookie driver.get('https://www.example.com') driver.add_cookie({'name': 'right', 'value': 'success'}) print('Cookie added after navigation') driver.quit()
Output
Error: You must navigate to a page before adding cookies
Cookie added after navigation
Quick Reference
- Use
driver.get()to open the domain before adding cookies. - Cookies must have
nameandvalue. - Use
driver.get_cookie(name)to verify a cookie. - Use
driver.delete_cookie(name)to remove a cookie.
Key Takeaways
Always navigate to the target website before adding cookies in Selenium.
Use a dictionary with at least 'name' and 'value' keys to add a cookie.
Verify cookies with get_cookie() after adding them.
Avoid adding cookies before page load to prevent errors.
Set optional cookie attributes like 'path' and 'expiry' as needed.