Home > database >  How to exit selenium chrome driver when exiting python script?
How to exit selenium chrome driver when exiting python script?

Time:03-11

I am running the flathunter script everyday for 14 hours and it opens a chromedriver instance on each execution

enter image description here

If that is the case, new instaces of webdriver may fail because of "port already in use" error.

Is it possible to run the webdriver in python in such a way, that it closes the webdriver process when the flathunter.py is exiting (either manually or because of failure)?

CodePudding user response:

Just before flathunter.py exists kill all of the ChromeDriver processes through proc.kill() as follows:

import os
import psutil

PROCNAME = "chromedriver" # or geckodriver or IEDriverServer
for proc in psutil.process_iter():
    # check whether the process name matches
    if proc.name() == PROCNAME:
        proc.kill()

CodePudding user response:

You can wrap all your Selenium code with try-except-finally block. In the finally block you can put a driver.close() method so that it will close the driver process in case of uncaught exception / failure.
The disadvantage of this approach is that this may cause difficulties with catching the failures with reports listeners.

  • Related