In Python, how to check if Selenium WebDriver has quit or not?

Viewed 6541

Following is the sample code:

from selenium import webdriver

driver = webdriver.Firefox()

(The window gets closed due to some reason here)

driver.quit()

Traceback (most recent call last): File "", line 1, in File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/firefox/webdriver.py", line 183, in quit RemoteWebDriver.quit(self) File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 592, in quit self.execute(Command.QUIT) File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 297, in execute self.error_handler.check_response(response) File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/errorhandler.py", line 194, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.WebDriverException: Message: Tried to run command without establishing a connection

Is there some way to check if an instance of webdriver is active?

4 Answers

be Pythonic... try to quit and catch the exception if it fails.

try:
    driver.quit()
except WebDriverException:
    pass

You can use something like this which uses psutil

from selenium import webdriver
import psutil

driver = webdriver.Firefox()

driver.get("http://tarunlalwani.com")

driver_process = psutil.Process(driver.service.process.pid)

if driver_process.is_running():
    print ("driver is running")

    firefox_process = driver_process.children()
    if firefox_process:
        firefox_process = firefox_process[0]

        if firefox_process.is_running():
            print("Firefox is still running, we can quit")
            driver.quit()
        else:
            print("Firefox is dead, can't quit. Let's kill the driver")
            firefox_process.kill()
    else:
        print("driver has died")

This is what I figured out and liked:

def setup(self):
    self.wd = webdriver.Firefox()

def teardown(self):
    # self.wd.service.process == None if quit already.
    if self.wd.service.process != None:
        self.wd.quit()

Note: driver_process=psutil.Process(driver.service.process.pid) will throw exception if driver already quits.

The answer by Corey Golberg is the correct way.

However if you really need to look under the hood, the driver.service.process property gives access to the underlying Popen object that manages the open browser. If the process has quit, the process property will be None and testing whether it is truthy will identify the state of the browser:

from selenium import webdriver
driver = webdriver.Firefox()

# your code where the browser quits

if not driver.service.process:
    print('Browser has quit unexpectedly')

if driver.service.process:
    driver.quit()
Related