How do I manage cookies in Selenium WebDriver?

In Selenium WebDriver, managing cookies is an important part of automating web browsers, as cookies store session information that can be crucial for accessing certain parts of a website. Selenium provides a way to interact with cookies using its API. Below are examples of how to manage cookies in both Python and Java, which are among the most popular languages used with Selenium.


First, you need to have Selenium installed. If you haven't installed it, you can do so using pip:

pip install selenium

Here's how you can manage cookies with Selenium in Python:

from selenium import webdriver

# Start a browser session
driver = webdriver.Chrome()

# Go to a website

# Set a cookie
driver.add_cookie({"name": "key", "value": "value"})

# Get a cookie by name
cookie = driver.get_cookie("key")

# Get all cookies
all_cookies = driver.get_cookies()

# Delete a cookie by name

# Delete all cookies

# Close the browser


If you're using Java, you will need to have the Selenium Java client and WebDriver binaries. You can add the Selenium Java client to your project using Maven by adding the following dependency to your pom.xml:


Here's a Java example of managing cookies in Selenium:

import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;

public class CookieManager {
    public static void main(String[] args) {
        // Start a browser session
        WebDriver driver = new ChromeDriver();

        // Go to a website

        // Set a cookie
        Cookie cookie = new Cookie("key", "value");

        // Get a cookie by name
        Cookie getCookie = driver.manage().getCookieNamed("key");

        // Get all cookies
        Set<Cookie> allCookies = driver.manage().getCookies();

        // Delete a cookie by name

        // Delete all cookies

        // Close the browser

Notes on Managing Cookies

  • Cookies can only be set if you are on the domain that the cookie will be valid for. If you try to set a cookie for a domain that is different from the current domain, it will not be set.
  • When setting a cookie, you can also specify additional properties such as path, domain, secure, httpOnly, and expiry.
  • It's important to note that managing cookies will not work with every browser and driver combination. For example, some drivers may not allow you to view secure or HttpOnly cookies for security reasons.

Make sure to review the documentation for the specific WebDriver you are using to understand its capabilities and limitations regarding cookie management.

Related Questions

Get Started Now

WebScraping.AI provides rotating proxies, Chromium rendering and built-in HTML parser for web scraping