Is there a way that for different runs of a python program that uses selenium I keep the browser that I have opened and logged in with my credentials, open and use in later runs?
I am debugging a code. On the browser each time I need to log in using my credentials. Currently, everytime I stop the code, the web-browser gets closed. Is there a way to keep a copy of browser that I have already open and logged in open and use it for my later debug so every time I don't need to enter my login credentials again?
My code that opens the browser looks like this:
driver = webdriver.Chrome(executable_path="/the_path/chromedriver", chrome_options=chrome_options)
driver.get(url)
EDIT:
Actually, the way this website asks for authentication is as follows:
First, it asks for the username, then I need to press the continue button, then it asks for the password, after entering the password, it sends an SMS to my phone, I need to enter it before it goes to the intended page.
解决方案
Well, since this question is upvoted but my flag as duplicated question wasn't accepted I will post here the same exact answer I already posted for a similar question:
You can use pickle to save cookies as text file and load it after:
def save_cookie(driver, path):
with open(path, 'wb') as filehandler:
pickle.dump(driver.get_cookies(), filehandler)
def load_cookie(driver, path):
with open(path, 'rb') as cookiesfile:
cookies = pickle.load(cookiesfile)
for cookie in cookies:
driver.add_cookie(cookie)
With a script like:
from selenium import webdriver
from afile import save_cookie
driver = webdriver.Chrome()
driver.get('http://website.internets')
foo = input()
save_cookie(driver, '/tmp/cookie')
What you can do is:
Run this script
On the (selenium's) browser, go to the website, login
Go back to your terminal, type anything hit enter.
Enjoy your cookie file at /tmp/cookie. You can now copy it into your code repo and package it into your app if needed.
So, now, in your main app code:
from afile import load_cookie
driver = webdriver.Chrome()
load_cookie(driver, 'path/to/cookie')
And you are now logged.