Stay logged in(save session) in new browser with Python Selenium

Viewed 1121

So, I am trying to:

  1. Open browser
  2. Log-In to website
  3. Save session/cookies
  4. Close browser
  5. Open new browser
  6. Load session/cookies and get logged in

I am trying to do this for hours, and it looks like old code from the internet doesn't work.

Code example:

import pickle
from webdriver_manager.chrome import ChromeDriverManager
from selenium import webdriver

# I am using website ascension.gg to test it, as it is very simple
browser = webdriver.Chrome(ChromeDriverManager().install()) 
browser.get('https://ascension.gg/')
time.sleep(20) # during this time, I log in manually
pickle.dump(browser.get_cookies() , open("asc2.pkl","wb")) # save cookies/session ideally
browser.quit()
browser = webdriver.Chrome(ChromeDriverManager().install()) 
browser.get('https://ascension.gg/')
for cookie in pickle.load(open("asc2.pkl", "rb")):
    browser.add_cookie(cookie) # load cookies and restore session
browser.refresh() # logged in back ( doesn't work )

Any help? Why this doesn't work? Thank you in advance.

1 Answers

How about using the chrome profile, which internally handles cookies.

ChromeOptions options = new ChromeOptions();
# location for a chrome profile creation/access
options.AddArguments(@"user-data-dir=/home/your_id/CHROME_STORAGE");
ChromeDriver driver = new ChromeDriver(options);

This code creates a save location for a profile (including a space for cookies). You do not need to write any manual codes for handling cookies with the above code. Instead, Chrome will handle cookies.

Related