Mindfulness

Clear Cookies in Python Using Selenium and Requests

Updated · By the Relaxmid editors

Reading time
5 min
Sections
7
Topic
Mindfulness

To clear cookies in Python, you use the delete_all_cookies() method if you are using Selenium, or you simply omit the cookie jar when using the Requests library. The method depends entirely on whether you are automating a live browser or sending raw HTTP requests.

Clearing Browser Cookies with Selenium

Selenium controls a real web browser, which means it manages a session just like a human user does. When you navigate to a site, the browser stores cookies to remember your login state or preferences. To remove these, you must first have the browser instance open and navigated to the domain you wish to clear.

The command driver.delete_all_cookies() removes every cookie associated with the current domain. This is a critical step when you need to test a website from a fresh, unauthenticated state without restarting the entire browser process. Restarting the driver takes more time and system resources than simply clearing the cookies.

If you only need to remove a specific cookie rather than all of them, you can use driver.delete_cookie('cookie_name'). This allows you to target a single session ID or a tracking token while keeping other preferences intact. This precision is useful when testing how a site behaves when a specific piece of data is missing but the user is still otherwise recognized.

Handling Cookies in Requests

The Requests library does not use a browser, so it does not have a persistent cookie store unless you explicitly create one. By default, every time you call requests.get() or requests.post(), the request is stateless. This means cookies are not saved between different calls, effectively starting every single request with a clear slate.

To maintain cookies across multiple requests, you use a Session object. A session automatically collects cookies sent by the server and sends them back in subsequent requests. To clear these cookies, you can either delete the session object and create a new one or clear the cookies attribute of the session.

Using session.cookies.clear() wipes the session’s cookie jar. This is the equivalent of clicking Clear History in a browser but only for that specific Python script’s memory. Once cleared, the next request sent via that session will be treated by the server as coming from a brand new visitor.

Worked Example for Session Management

Imagine you are testing a login flow where you must first log in, perform an action, and then ensure the logout function actually clears the session. In this scenario, you would use a session object to track the cookies.

  1. Create a session: session = requests.Session().
  2. Post login credentials to the server. The server sends back a session cookie, which the Session object stores automatically.
  3. Perform a protected action, such as visiting /account/profile. The session sends the cookie, and the server grants access.
  4. Call the logout endpoint. The server may send a command to expire the cookie, but for total certainty in your script, you call session.cookies.clear().
  5. Attempt to visit /account/profile again. Because the cookies are gone, the server will return a 401 Unauthorized or 302 Redirect to the login page.

In this example, the arithmetic of the session is simple: 1 session object manages N cookies. When you call clear(), N becomes 0. This ensures that no residual data from the first user interferes with the second test case.

Common Cookie Misconceptions

A frequent misconception is that driver.delete_all_cookies() in Selenium clears the browser’s global cache or history. This is not true. This command only removes the cookies for the domain currently loaded in the browser window. It does not delete the browser cache, local storage, or session storage.

To clear local storage or session storage, you must execute JavaScript through the driver. For example, using driver.execute_script("window.localStorage.clear();") removes data stored in the browser’s local storage. These are separate mechanisms from cookies, although they are often used for similar purposes. If you only clear cookies but leave local storage intact, some websites may still recognize you because they store your identity token in the local storage instead of a cookie.

Managing Cookie Domains and Paths

Cookies are not always global to a site; they are often restricted by domain and path. A cookie set for blog.example.com may not be visible or clearable when the browser is navigated to shop.example.com. When using Python to clear cookies, ensure your driver is on the correct subdomain.

The path attribute further restricts cookies. A cookie set for the path /admin will not be sent to the server when you visit /home. While delete_all_cookies() typically handles all paths for the current domain, manual deletion via delete_cookie('name') requires the cookie to be accessible at the current URL. If the cookie is locked to a specific path, you must navigate to that path before the deletion command will work.

For those using the Requests library, the CookieJar handles these complexities automatically. When you clear the jar, it removes all entries regardless of domain or path. This makes the Requests approach more straightforward for API testing, while the Selenium approach requires more attention to the browser’s current state.

Cookie Automation for Testing

When building a test suite, you should clear cookies in the setUp or tearDown phase of your tests. This prevents “leaky tests,” where a cookie from Test A allows Test B to pass even though the login logic in Test B is actually broken. By starting every test with a clean cookie jar, you ensure that each test is independent and reproducible.

If you are scraping a site that uses cookies to track and block bots, clearing cookies periodically can help you appear as a new user. However, some sites track IP addresses or browser fingerprints. In those cases, clearing cookies alone is not enough. You would need to combine cookie clearing with the use of a proxy or a different user-agent string to fully reset your identity.

To check if cookies were successfully cleared in Selenium, you can print the length of the cookie list: print(len(driver.get_cookies())). If the result is 0, the operation was successful. In Requests, you can check len(session.cookies) to verify the jar is empty. This simple check adds a layer of verification to your automation scripts, ensuring that your environment is truly reset before the next action begins.

Related

General information for everyday wellbeing, not medical advice. If something affects your health, sleep or mood for more than a short while, talk to a qualified professional. Read more

Spotted an error? Tell us and we will correct it (corrections policy).