Reputation: 347
The following line of code is executed in my Python script:
driver = webdriver.Chrome(CHROMEDRIVER_PATH, chrome_options = chrome_options)
This line may either fail or succeed, depending on apparently random conditions (It is due to an extension that is being loaded, but that is not relevant here).
The problem is that even if this line fails, and raises a WebDriverException
, an instance of Chromium will still be spawned, eventually flooding my entire desktop because I am running this line in a while loop until it works.
The following block of code does not work because driver is not defined.
try:
driver = webdriver.Chrome(CHROMEDRIVER_PATH, chrome_options = chrome_options)
except WebDriverException:
driver.quit()
How to do this in a clever way?
Upvotes: 4
Views: 6149
Reputation: 193388
As you mentioned you have the following line :
driver = webdriver.Chrome(CHROMEDRIVER_PATH, chrome_options = chrome_options)
And this line may either fail
or succeed
. So there are 2 usecases which can be addressed as follows :
Success
: Incase the above mentioned line of code is Success
we will use driver.quit()
straight away as follows :
try:
driver = webdriver.Chrome(CHROMEDRIVER_PATH, chrome_options = chrome_options)
#other code
driver.quit()
Failure
: Incase the above mentioned line of code is Failure
we will use the taskkill command from os module to force-kill the chromedriver
process
straight away as follows :
import os
#other code
try:
driver = webdriver.Chrome(CHROMEDRIVER_PATH, chrome_options = chrome_options)
#other code
driver.quit()
except WebDriverException:
os.system("taskkill /im chromedriver.exe")
Through the command webdriver.Chrome(CHROMEDRIVER_PATH, chrome_options = chrome_options)
irrespective of whether Chromium
session is spawned or not, a separate chromedriver
session will be always spawned which we have taken care in our code. If you want to kill the Chromium
session as well, you have to add the following line as well :
os.system("taskkill /im chrome.exe")
Upvotes: 1