How to retrieve and add cookies for login activity on selenium scripts?

When automating the web pages, user may have the scenario for login page.  To enter the login and password user need to enter the details each and every time for logging in.

For example, If we want to login with Facebook or Google sign in page everytime, we can use the cookies to retrieve the user id and password.  Browser will remember the login and password details using cookies.

We need not to enter the user and password everytime, we just need to add the cookies on the script for logging in.  It will be interesting when we execute the below code.  Just try with the facebook account.

Please replace your user id and password for your facebook or google or pinterest or twitter login.

JAVA Syntax : driver.manage().getCookies();

getCookies() method will collect all the details from the cookies of the user id and password details which stores on the current session.

Code to collect the cookies :-
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class GetCookies {
private static WebDriver driver = null;

public static void main(String args[]) {

//Invoke Driver
driver.get("http://facebook.com");
 
//Enter  Login Credentials
driver.findElement(By.name("email")).sendKeys("*****Your Email ID*****");
driver.findElement(By.name("pass")).sendKeys("*****Your Password");
 
//Click login
driver.findElement(By.name("LogIn")).submit();
 
//To get the cookies and store 
File fl = new File("browser.data");
try{
 
fl.delete();
fl.createNewFile();

FileWriter fw = new FileWriter(fl);
BufferedWriter bw = new BufferedWriter(fw);

for(Cookie ckie : driver.manage().getCookies()) {
bw .write((ckie.getName()+";"+ckie.getValue()+";"+ckie.getDomain()
+";"+ckie.getPath()+";"+ckie.getExpiry()+";"+ckie.isSecure()));

//Printing into console
System.out.println(ckie.getName()+";"+ckie.getValue()+";"+ckie.getDomain()
+";"+ckie.getPath()+";"+ckie.getExpiry()+";"+ckie.isSecure());
bw.newLine();
}

bw.flush();
bw.close();
fw.close();
}catch(Exception ex){
ex.printStackTrace();
}
}
}

No comments:

Post a Comment

Socialize It and Share the post with your friends
SOCIALIZE IT →
FOLLOW US →
SHARE IT →