Adding and Deleting Cookies in Selenium Python
Last Updated :
04 Jun, 2025
Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provide a simple API to write functional/acceptance tests using Selenium WebDriver.
Selenium WebDriver provides several methods to control the browser session, such as adding cookies, navigating back, switching tabs, and more. Managing cookies is often an important part of testing, especially when simulating scenarios like authentication where cookies may need to be manually added or removed. Selenium’s Python WebDriver offers methods to add, retrieve, and delete cookies, enabling testers to handle various practical use cases efficiently.
Cookie Methods in Selenium
Selenium WebDriver provides various methods to manage cookies.
1. add_cookie driver method
add_cookie
method is used to add a cookie to your current session. This cookie can be used by website itself or by you.
Syntax -
add_cookie(cookie_dict)
Example - Now one can use add_cookie method as a driver method as below -
driver.add_cookie({‘name’ : ‘foo’, ‘value’ : ‘bar’})
Read More - add_cookie driver method.
2. get_cookie driver method
get_cookie
method is used to get a cookie with a specified name. It returns the cookie if found, None if not.
Syntax -
driver.get_cookie(name)
Example - Now one can use get_cookie method as a driver method as below -
driver.get("https://www.geeksforgeeks.org/")
driver.get_cookie("foo")
Read More - get_cookie driver method.
3. delete_cookie driver method
delete_cookie
method is used to delete a cookie with a specified value.
Syntax -
driver.delete_cookie(name)
Example - Now one can use delete_cookie method as a driver method as below -
driver.get("https://www.geeksforgeeks.org/")
driver.delete_cookie("foo")
Read More - delete_cookie driver method.
4. get_cookies driver method
get_cookies
method is used to get all cookies in current session. It returns a set of dictionaries, corresponding to cookies visible in the current session. Syntax -
driver.get_cookies()
Example - Now one can use get_cookies method as a driver method as below -
driver.get("https://www.geeksforgeeks.org/")
driver.get_cookies()
Read More - get_cookies driver method.
Example 1: Adding and Verifying a Cookie
We will demonstrate these methods by testing cookie management on https://www.geeksforgeeks.org, We’ll add a cookie, retrieve it, verify its presence, and delete it.
Java
package ActionsTest;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
public class Example_LoginTest {
public static void main(String[] args) {
// Optional: Set path to chromedriver if not already in system PATH
// System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
// Setup Chrome options (start maximized)
ChromeOptions options = new ChromeOptions();
options.addArguments("--start-maximized");
// Initialize WebDriver
WebDriver driver = new ChromeDriver(options);
try {
// Navigate to the website
driver.get("https://www.geeksforgeeks.org/");
// Add a cookie
Cookie cookie = new Cookie.Builder("foo", "bar").build();
driver.manage().addCookie(cookie);
System.out.println("Cookie added: {'name': 'foo', 'value': 'bar'}");
// Retrieve the cookie
Cookie retrievedCookie = driver.manage().getCookieNamed("foo");
System.out.println("Retrieved cookie: " + retrievedCookie);
// Verify the cookie
if (retrievedCookie != null &&
"foo".equals(retrievedCookie.getName()) &&
"bar".equals(retrievedCookie.getValue())) {
System.out.println("Cookie verification passed!");
} else {
System.out.println("Cookie verification failed!");
}
} finally {
// Close the browser
driver.quit();
}
}
}
Python
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
# Set up ChromeDriver
options = Options()
options.add_argument("--start-maximized")
driver = webdriver.Chrome(options=options)
try:
# Navigate to the website
driver.get("https://www.geeksforgeeks.org/")
# Add a cookie
driver.add_cookie({'name': 'foo', 'value': 'bar'})
print("Cookie added: {'name': 'foo', 'value': 'bar'}")
# Get the specific cookie
cookie = driver.get_cookie("foo")
print("Retrieved cookie:", cookie)
# Verify the cookie
if cookie and cookie['name'] == 'foo' and cookie['value'] == 'bar':
print("Cookie verification passed!")
else:
print("Cookie verification failed!")
finally:
# Close the browser
driver.quit()
Output:
Output of Adding and Verifying a CookieExample 2: Managing All Cookies and Deleting One
We will demonstrate List all cookies, add a custom cookie, delete it, and confirm its removed or not.
Java
package ActionsTest;
import java.util.Set;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
public class CookieManagementTest {
public static void main(String[] args) {
// Optional: Set path to chromedriver if not in system PATH
// System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
// Setup Chrome options (start maximized)
ChromeOptions options = new ChromeOptions();
options.addArguments("--start-maximized");
WebDriver driver = new ChromeDriver(options);
try {
// Navigate to the website
driver.get("https://www.geeksforgeeks.org/");
// Get all cookies initially
Set<Cookie> initialCookies = driver.manage().getCookies();
System.out.println("Initial cookies: " + initialCookies);
// Add a cookie
Cookie cookie = new Cookie.Builder("foo", "bar").build();
driver.manage().addCookie(cookie);
// Get cookies after adding
Set<Cookie> afterAddCookies = driver.manage().getCookies();
System.out.println("After adding 'foo': " + afterAddCookies);
// Delete the cookie named "foo"
driver.manage().deleteCookieNamed("foo");
// Get cookies after deletion
Set<Cookie> afterDeleteCookies = driver.manage().getCookies();
System.out.println("After deleting 'foo': " + afterDeleteCookies);
// Verify deletion
Cookie retrievedCookie = driver.manage().getCookieNamed("foo");
if (retrievedCookie == null) {
System.out.println("Cookie 'foo' successfully deleted!");
} else {
System.out.println("Cookie 'foo' still exists!");
}
} finally {
driver.quit();
}
}
}
Python
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
# Set up ChromeDriver
options = Options()
options.add_argument("--start-maximized")
driver = webdriver.Chrome(options=options)
try:
# Navigate to the website
driver.get("https://www.geeksforgeeks.org/")
# Get all cookies
print("Initial cookies:", driver.get_cookies())
# Add a cookie
driver.add_cookie({'name': 'foo', 'value': 'bar'})
print("After adding 'foo':", driver.get_cookies())
# Delete the cookie
driver.delete_cookie("foo")
print("After deleting 'foo':", driver.get_cookies())
# Verify deletion
if not driver.get_cookie("foo"):
print("Cookie 'foo' successfully deleted!")
else:
print("Cookie 'foo' still exists!")
finally:
driver.quit()
Output:
Output of Managing All Cookies and Deleting OneManaging cookies in Selenium Python is straightforward with methods like add_cookie(), get_cookie(), delete_cookie(), and get_cookies(). These will let you simulate user sessions, test authentication, and verify personalization, making your tests faster and reliable.
Similar Reads
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read