I am running a Flask server and I have the following problem.
When an user login in, a Selenium webdriver
is initialized and performs some task. It store some cookies and then it communicates with frontend (I can't control WHEN it will save the cookies and I cannot close it with driver.close()
. After this I need to start again the chromedriver
but preserving the cookies (I'm using User dir
for this reason and this works).
The problem is that the second time I start the webdriver
I get error because the previous one is not closed. How can I close it before starting a new one, using Python?
Thanks!
I expect to close all the active chromedriver
sessions without using Selenium (I cannot use it), but using Python.
CodePudding user response:
You can save the cookies ina txt file, and every time you run the drive, you add the cookies with 'driver.get_cookies()', 'drive.add_cookie()' and these structure:
content_cookies = {
'name': <NAME_VARIABLE_COOKIE>,
'domain': '<URLSITE>',
'value': str(<VALUE_VARIABLE_COOKIE>)
}
driver.add_cookie(content_cookies)
CodePudding user response:
Ideally, you want to driver.quit()
to gracefully close all browser windows (note that driver.close()
only closes the window in focus). If that's not possible, you can use psutil to kill the chromedriver processes:
for proc in psutil.process_iter():
if 'chromedriver' in proc.name():
proc.kill()
A similar approach can work with the built-in subprocess
, but maybe with a few extra steps depending on your OS.