To delete a particular (specific) cookie in Selenium Java, you have two main approaches:
1. Delete by Cookie Name
Use the deleteCookieNamed(String name)
method, passing the exact name of the cookie you wish to remove. This is the simplest and most common way.
Example:
// Delete cookie with the name "session_id"
driver.manage().deleteCookieNamed("session_id");
- The string must match the cookie’s name exactly. To check available cookie names, you can use
driver.manage().getCookies()
and print their names.
2. Delete by Cookie Object
If you have a Cookie object (for example, retrieved via getCookieNamed()
), use the deleteCookie(Cookie cookie)
method:
import org.openqa.selenium.Cookie;
// Get the cookie object by name
Cookie cookie = driver.manage().getCookieNamed("session_id");
if (cookie != null) {
driver.manage().deleteCookie(cookie);
}
- This approach is useful if you need to match a cookie not just by name but also by path, domain, or other attributes.
Complete Code
import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.Cookie; public class DeleteSpecificCookie { public static void main(String[] args) { WebDriver driver = new ChromeDriver(); driver.get("https://www.example.com"); // Delete by name: driver.manage().deleteCookieNamed("session_id"); // Or delete by Cookie object: Cookie cookie = driver.manage().getCookieNamed("user_token"); if (cookie != null) { driver.manage().deleteCookie(cookie); } driver.quit(); } }
Key Points:
- The name you provide must be the exact name of the cookie.
- These methods affect only cookies for the current domain loaded in the browser.
- Use
deleteCookieNamed()
for convenience, ordeleteCookie()
with aCookie
object for finer control.
This allows for precise, selective removal of cookies instead of clearing all cookies at once.