0
0
Selenium-pythonHow-ToBeginner ยท 3 min read

How to Delete Cookie in Selenium: Syntax and Examples

In Selenium, you can delete cookies using the deleteCookieNamed() method to remove a specific cookie by name or deleteAllCookies() to clear all cookies. These methods are called on the WebDriver's manage() interface.
๐Ÿ“

Syntax

Use driver.manage().deleteCookieNamed(String name) to delete a specific cookie by its name. Use driver.manage().deleteAllCookies() to delete all cookies stored in the browser session.

Here, driver is your Selenium WebDriver instance.

java
driver.manage().deleteCookieNamed("cookieName");
driver.manage().deleteAllCookies();
๐Ÿ’ป

Example

This example shows how to open a website, add a cookie, delete a specific cookie by name, and then delete all cookies.

java
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class DeleteCookieExample {
    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver");
        WebDriver driver = new ChromeDriver();

        driver.get("https://www.example.com");

        // Add a cookie
        Cookie cookie = new Cookie("testCookie", "12345");
        driver.manage().addCookie(cookie);

        // Delete the cookie by name
        driver.manage().deleteCookieNamed("testCookie");

        // Delete all cookies
        driver.manage().deleteAllCookies();

        driver.quit();
    }
}
Output
The browser opens https://www.example.com, adds a cookie named 'testCookie', deletes it, then deletes all cookies before closing.
โš ๏ธ

Common Pitfalls

  • Trying to delete a cookie before the page loads can cause errors because cookies are tied to the current domain.
  • Deleting a cookie by a wrong or misspelled name will not throw an error but will not delete anything.
  • Remember to manage cookies only after navigating to a page; otherwise, the cookie store may be empty.
java
/* Wrong way: deleting cookie before loading page */
// driver.manage().deleteCookieNamed("testCookie"); // May not work

/* Right way: navigate first, then delete */
driver.get("https://www.example.com");
driver.manage().deleteCookieNamed("testCookie");
๐Ÿ“Š

Quick Reference

MethodDescription
deleteCookieNamed(String name)Deletes a cookie by its name.
deleteAllCookies()Deletes all cookies in the current session.
addCookie(Cookie cookie)Adds a cookie to the current domain.
getCookies()Retrieves all cookies for the current domain.
โœ…

Key Takeaways

Always navigate to a page before deleting cookies to ensure the cookie store is accessible.
Use deleteCookieNamed() to remove a specific cookie by name without errors if the cookie doesn't exist.
Use deleteAllCookies() to clear all cookies in the browser session.
Cookie operations are domain-specific; cookies from other domains cannot be deleted.
Check cookie names carefully to avoid silent failures when deleting.