How to handle Cookies using Selenium Webdriver?

  • Sometimes, we face issues because of cookies session created by Selenium scripts and we have to delete them using Selenium Webdriver. So, here is the code:

public class Cookies
{
    public static void main(String[] args) 
    {
        WebDriver driver=new FirefoxDriver();
        driver.get("http://in.quikr.com/");
        
        Set cookies=driver.manage().getCookies();
        
        //To fetch out the number of cookies used by this site
        System.out.println("Number of cookies in this site "+cookies.size());
        
     //Using advanced For Loop
        for(Cookie cookie:cookies)
        {
            System.out.println(cookie.getName()+" "+cookie.getValue());
            
            //This will delete cookie By Name
            driver.manage().deleteCookieNamed(cookie.getName());
            
             }
         //This will delete all cookies.
        driver.manage().deleteAllCookies();
           } }