0
votes

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?

3

3 Answers

2
votes

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")
2
votes

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

try:
    driver.quit()
except WebDriverException:
    pass
2
votes

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.