Cookies help websites remember you. Managing cookies in tests lets us check if the website saves and uses this info correctly.
0
0
Cookie management in Selenium Python
Introduction
When testing if a website keeps you logged in after closing and reopening the browser.
When checking if user preferences are saved and loaded correctly.
When verifying that cookies are deleted after logout.
When testing how the website behaves with specific cookie values set.
When automating tests that require setting cookies to skip certain steps.
Syntax
Selenium Python
driver.get_cookies()
driver.get_cookie(name)
driver.add_cookie({'name': 'key', 'value': 'value'})
driver.delete_cookie(name)
driver.delete_all_cookies()Use driver.get_cookies() to get all cookies as a list of dictionaries.
Cookies must have at least name and value when adding.
Examples
Get all cookies and print them as a list.
Selenium Python
cookies = driver.get_cookies()
print(cookies)Get a specific cookie by name and print it.
Selenium Python
cookie = driver.get_cookie('session_id') print(cookie)
Add a new cookie with name and value.
Selenium Python
driver.add_cookie({'name': 'test_cookie', 'value': '12345'})Delete a cookie by its name.
Selenium Python
driver.delete_cookie('test_cookie')Sample Program
This script opens a website, adds a cookie, prints it, prints total cookies, deletes the cookie, and checks it is gone.
Selenium Python
from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.chrome.options import Options import time options = Options() options.add_argument('--headless=new') service = Service() driver = webdriver.Chrome(service=service, options=options) try: driver.get('https://www.example.com') # Add a cookie driver.add_cookie({'name': 'mycookie', 'value': 'cookievalue'}) # Get and print the cookie cookie = driver.get_cookie('mycookie') print(cookie) # Get all cookies all_cookies = driver.get_cookies() print(f"Total cookies: {len(all_cookies)}") # Delete the cookie driver.delete_cookie('mycookie') # Verify deletion cookie_after_delete = driver.get_cookie('mycookie') print(cookie_after_delete) finally: driver.quit()
OutputSuccess
Important Notes
Cookies are domain-specific; you must be on the domain to add or get cookies.
Deleting a cookie removes it from the browser session immediately.
Use headless mode for faster tests without opening a browser window.
Summary
Cookies store small data for websites to remember you.
Selenium lets you add, get, and delete cookies during tests.
Managing cookies helps test login, preferences, and session behavior.