How the save the browser sessions in Selenium?

Viewed 11418

I am using Selenium to Log In to an account. After Logging In I would like to save the session and access it again the next time I run the python script so I don't have to Log In again. Basically I want to chrome driver to work like the real google chrome where all the cookies/sessions are saved. This way I don't have to login to the website on every run.

browser.get("https://www.website.com")
browser.find_element_by_xpath("//*[@id='identifierId']").send_keys(email)
browser.find_element_by_xpath("//*[@id='identifierNext']").click()
time.sleep(3)
browser.find_element_by_xpath("//*[@id='password']/div[1]/div/div[1]/input").send_keys(password)
browser.find_element_by_xpath("//*[@id='passwordNext']").click()
time.sleep(5)
3 Answers

As @MohamedSulaimaanSheriff already suggested, you can open Chrome with your personal chrome profile in selenium. To do that, this code will work:

options = webdriver.ChromeOptions()
options.add_argument(r'--user-data-dir=C:\Users\YourUser\AppData\Local\Google\Chrome\User Data\')
PATH = "/Users/yourPath/Desktop/chromedriver"
driver = webdriver.Chrome(PATH, options=options)

Of course you can setup extra User Data for your script by creating a new User Data Directory and replace the path. Make sure that you copy your existing User Data to ensure you're not provoking any errors. Afterwards you could reset them in Chrome itself.

This is the solution I used:

# I am giving myself enough time to manually login to the website and then printing the cookie
time.sleep(60)
print(driver.get_cookies())

# Than I am using add_cookie() to add the cookie/s that I got from get_cookies()
driver.add_cookie({'domain': ''})

This may not be the best way to implement it but it's doing what I was looking for

First login to the website and print your cookie with this:

print(driver.get_cookies())

Then try:

driver.get("<website>")
driver.add_cookie({'domain':''})
Related