Open In App

Adding and Deleting Cookies in Selenium Python

Last Updated : 04 Jun, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

Selenium WebDriver provides various methods to manage cookies.

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.

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.

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.

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-Selenium-handling-Cookies-with-python
Output of Adding and Verifying a Cookie

Example 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:

Screenshot-2025-06-02-135955
Output of Managing All Cookies and Deleting One

Managing 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.


Next Article
Practice Tags :

Similar Reads