How to Clear Cookies and Sessions with Selenium and PhantomJS
In this article
Clearing cookies and sessions in Selenium tests with PhantomJS ensures each test run starts with a clean browser state, preventing data leakage between tests and avoiding false positives or negatives. This guide shows you how to delete all cookies, clear session storage, and reset the browser context using PhantomJS's WebDriver implementation.
What You'll Need
- Python 3.x (or Java, but examples here are in Python)
- Selenium WebDriver installed (
pip install selenium) - PhantomJS binary downloaded from phantomjs.org (version 2.1.1 is the last stable release)
- A basic understanding of Selenium WebDriver commands
Step-by-Step
- Import Selenium and initialize PhantomJS
Start by importing the WebDriver module and creating a PhantomJS driver instance. Make sure the PhantomJS executable is in your PATH or specify its location explicitly. - Navigate to a page (or use about:blank)
PhantomJS requires a page to be loaded before you can interact with cookies or storage. Usedriver.get('about:blank')or navigate to your test URL. The page must be loaded for the WebDriver to have a browsing context. - Delete all cookies
Calldriver.delete_all_cookies(). This removes every cookie for the current domain and all subdomains. If you need to delete a specific cookie, usedriver.delete_cookie(name). - Clear session storage
Selenium's WebDriver API does not directly expose sessionStorage, but you can execute JavaScript to clear it. Usedriver.execute_script("window.sessionStorage.clear();"). This removes all key-value pairs stored in sessionStorage for the current origin. - Clear local storage (optional but recommended)
Similarly, clear localStorage withdriver.execute_script("window.localStorage.clear();"). This is not strictly a session, but it often contains authentication tokens or user preferences that can affect tests. - Reset browser context (if using PhantomJS 2.x)
PhantomJS does not have a built-in "new incognito window" command, but you can simulate a fresh session by creating a new driver instance. However, if you want to keep the same driver, you can also usedriver.manage().delete_all_cookies()and clear storage as above. - Verify the cleanup
To confirm that cookies are gone, retrieve all cookies withdriver.get_cookies()and assert it returns an empty list. For storage, executewindow.sessionStorage.lengthandwindow.localStorage.lengthand check they are 0. - Close the driver when done
Always calldriver.quit()after your tests to free resources. If you are running multiple tests, you can reuse the same driver after clearing, but be aware that PhantomJS may retain some internal state.
Common Mistakes
- Not navigating to a page first – PhantomJS throws an error if you try to access cookies or storage without a loaded page.
- Only clearing cookies, not storage – Many modern apps store session tokens in localStorage or sessionStorage, so clearing only cookies may not fully reset the session.
- Using
delete_all_cookies()on a different domain – If you navigate to a new domain, cookies from the previous domain are not cleared automatically. You must call the method while on the domain you want to clear. - Assuming PhantomJS supports the same commands as Chrome/Firefox – PhantomJS is an older WebDriver implementation; some commands like
driver.manage().delete_all_cookies()work, but others likedriver.manage().window().maximize()may not be implemented. - Not clearing storage after each test – If you reuse the same driver across tests, you must clear both cookies and storage between tests, otherwise state leaks.
Tips
- Use a fixture or setup method – In your test framework (pytest, unittest), create a setup that clears cookies and storage before each test to ensure isolation.
- Consider using a fresh driver per test – While PhantomJS is lightweight, creating a new instance per test is the simplest way to guarantee a clean session. The overhead is minimal compared to Chrome or Firefox.
- Combine with a proxy or cookie jar – If you need to simulate a user with specific cookies, use
driver.add_cookie()after clearing to inject a known session. - Use JavaScript to clear storage only on the current origin – If your test navigates across multiple origins, you need to clear storage on each origin separately.
- Log the cookie count before and after – This helps debug if the clearing is not working as expected.
Troubleshooting
- "Invalid cookie domain" error – This happens when you try to add a cookie for a domain that is not the current page. Always navigate to the correct domain first.
- Storage.clear() does not work – In some PhantomJS versions,
window.sessionStorage.clear()may not exist. Use a fallback: iterate over keys and remove them individually viaremoveItem(). - Cookies reappear after clearing – If a page sets cookies via JavaScript on load, they will reappear after you clear them. Clear cookies after the page load, or use a blank page to avoid this.
- Driver crashes after clearing – PhantomJS is known to be unstable. If you encounter crashes, try upgrading to a newer browser driver like ChromeDriver or GeckoDriver, as PhantomJS is no longer actively maintained.
- Session still persists after clearing – Some servers use HTTP-only cookies that are not accessible via JavaScript, but
delete_all_cookies()should still remove them. If not, the server may be using a different mechanism like HTTP authentication, which cannot be cleared via WebDriver.
Frequently Asked Questions
Does PhantomJS support Selenium WebDriver natively?
Yes, PhantomJS has a built-in WebDriver mode that allows Selenium to control it. You just need to download the binary and point Selenium to it.
Can I clear cookies without navigating to a page?
No, you must have a page loaded because WebDriver requires a browsing context to execute commands. Use about:blank if you don't want to load your test page.
Is delete_all_cookies() enough to clear a session?
Not always. Many modern web apps store session tokens in localStorage or sessionStorage, so you need to clear those as well.
Why does my session still exist after clearing cookies?
It could be because the server uses a token in localStorage, or the session is maintained via a server-side session ID that is not stored in a cookie (e.g., HTTP Basic Auth). Check the browser's storage.
Is PhantomJS still recommended for new projects?
No, PhantomJS is no longer maintained. For new projects, use headless Chrome or Firefox with Selenium, as they are more reliable and support modern web standards.
Can I clear cookies and sessions in a single command?
No, there is no single command. You need to combine delete_all_cookies() and JavaScript execution to clear storage.