3

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)
MA19112001
  • 106
  • 3
  • 13
  • Does this answer your question? [Python: use cookie to login with Selenium](https://stackoverflow.com/questions/45417335/python-use-cookie-to-login-with-selenium) – Celius Stingher Aug 13 '20 at 16:40
  • You can get chrome browser default profile path when it is launched with selenium and you can set this a `user-data-dir` for next launch which will load all cookies. To get chrome cookie file path https://sqa.stackexchange.com/questions/45192/how-to-get-the-chrome-browser-cookie-file-path-when-it-is-launched-from-selenium/45196#45196 – Mohamed Sulaimaan Sheriff Aug 13 '20 at 17:59

2 Answers2

6

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.

Ruben Helsloot
  • 11,812
  • 5
  • 19
  • 40
benicamera
  • 436
  • 1
  • 3
  • 19
0

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

MA19112001
  • 106
  • 3
  • 13