nafas
nafas

Reputation: 5423

Crawling using selenium: How to keep logged in after close Driver in java

is there anyway that driver Could remember the logged in session, so it doesn't take me back to Login page (e.g. like google-chrome)?

this is what I'm doing at the moment

public static void main(String[] args) throws Exception {

  driver = new ChromeDriver();

  // I get redirected to login page 
  driver.get("http://localhost/interestingStuff"); 
    
  // logins in to the page and submits(note I try to omit this part if possible).
  login();

  doStuff();
     
  //I want to be able to keep session next time I start this program.
  driver.close(); 

}

Upvotes: 5

Views: 11223

Answers (2)

alboforlizo
alboforlizo

Reputation: 361

I was able to keep session data by defining the driver option "--user-data-dir" as in following snippet:

ChromeOptions options = new ChromeOptions();
options.addArguments("--user-data-dir=C:\\ChromeDriver");
this.driver = new ChromeDriver(options);

You can even define different profiles by means of the "--profile-directory" option:

options.add_argument('--profile-directory=Profile 1')

Upvotes: 0

Andrew
Andrew

Reputation: 11446

Selenium with default configuration creates for every session temporary profile and delete this temp files after work.

So if you want to save cookies (remmember "logged in session") you need to go by one of the following ways:

  1. Use the same Chrome driver profile created earlier ( Load Chrome Profile using Selenium WebDriver using java )
  2. Create external class for save cookies to some file (c# solution here: Keep user logged in - save cookies using web driver )
  3. Do binary Serialyzation of cookies if this is possible and deserialyze when needed

Upvotes: 9

Related Questions