CptNemo
CptNemo

Reputation: 6755

Python Selenium: How to check whether the WebDriver did quit()?

I want to control whether my WebDriver quit but I can't find a method for that. (It seems that in Java there's a way to do it)

from selenium import webdriver
driver = webdriver.Firefox()
driver.quit()
driver # <selenium.webdriver.firefox.webdriver.WebDriver object at 0x108424850>
driver is None # False

I also explored the attributes of WebDriver but I can't locate any specific method to get information on the driver status. Also checking the session id:

driver.session_id # u'7c171019-b24d-5a4d-84ef-9612856af71b'

Upvotes: 18

Views: 32539

Answers (9)

Emile Durkheim
Emile Durkheim

Reputation: 435

In my case, I needed to detect whether the browser interface was closed - regardless - chromedriver's status. As such, none of the answers here worked, and I just decided to go for the obvious:

from selenium.common.exceptions import WebDriverException

try:
    driver.current_url
    print('Selenium is running')
except WebDriverException:
    print('Selenium was closed')

Even though it's a bit of a hack, it's served my purposes perfectly.

Upvotes: 0

Matias Bertani
Matias Bertani

Reputation: 99

This work for me:

from selenium import webdriver

driver = webdriver.Chrome()
print( driver.service.is_connectable()) # print True

driver.quit()
print( driver.service.is_connectable()) # print False

Upvotes: 9

sdfasdf
sdfasdf

Reputation: 1

''''python def closedriver(): global drivername drivername.quit() global driveron driveron=False '''' this function "closedriver" uses a global variable named "drivername" and global bool variable named "driveron",you may just pass a current driver as parameter but
NOTE: driveron must be global to store the state of driver being 'on' or 'off'. ''''python
def closedriver(drivername):
global driveron
try:
drivername.quit()
except:
pass
driveron=False
''''
and when you start a new driver, just use a check
global driveron
if not driveron:
driver=webdriver.Chrome()

Upvotes: -2

CodingMatters
CodingMatters

Reputation: 1431

suggested methods above didn't work for me on selenium version 3.141.0

dir(driver.service) found a few useful options 

driver.session_id   
driver.service.process
driver.service.assert_process_still_running()
driver.service.assert_process_still_running 

I found this SO question when I had a problem with closing an already closed driver, in my case a try catch around the driver.close() worked for my purposes.

try:
    driver.close()
    print("driver successfully closed.")
except Exception as e:
    print("driver already closed.")

also:

import selenium
help(selenium)

to check selenium version number

Upvotes: 2

Rimfire
Rimfire

Reputation: 400

There is this function:

if driver.service.isconnectible(): print('Good to go')

Upvotes: 0

Freshman
Freshman

Reputation: 149

I ran into the same problem and tried returning the title - this worked for me using chromedriver...

from selenium.common.exceptions import WebDriverException

try:
    driver.title
    print(True)
except WebDriverException:
    print(False)

Upvotes: 14

sergiussergius
sergiussergius

Reputation: 21

it works in java, checked on FF

((RemoteWebDriver)driver).getSessionId() == null

Upvotes: 0

alecxe
alecxe

Reputation: 474171

If you would explore the source code of the python-selenium driver, you would see what the quit() method of the firefox driver is doing:

def quit(self):
    """Quits the driver and close every associated window."""
    try:
        RemoteWebDriver.quit(self)
    except (http_client.BadStatusLine, socket.error):
        # Happens if Firefox shutsdown before we've read the response from
        # the socket.
        pass
    self.binary.kill()
    try:
        shutil.rmtree(self.profile.path)
        if self.profile.tempfolder is not None:
            shutil.rmtree(self.profile.tempfolder)
    except Exception as e:
        print(str(e))

There are things you can rely on here: checking for the profile.path to exist or checking the binary.process status. It could work, but you can also see that there are only "external calls" and there is nothing changing on the python-side that would help you indicate that quit() was called.

In other words, you need to make an external call to check the status:

>>> from selenium.webdriver.remote.command import Command
>>> driver.execute(Command.STATUS)
{u'status': 0, u'name': u'getStatus', u'value': {u'os': {u'version': u'unknown', u'arch': u'x86_64', u'name': u'Darwin'}, u'build': {u'time': u'unknown', u'version': u'unknown', u'revision': u'unknown'}}}
>>> driver.quit()
>>> driver.execute(Command.STATUS)
Traceback (most recent call last):
...
socket.error: [Errno 61] Connection refused

You can put it under the try/except and make a reusable function:

import httplib
import socket

from selenium.webdriver.remote.command import Command

def get_status(driver):
    try:
        driver.execute(Command.STATUS)
        return "Alive"
    except (socket.error, httplib.CannotSendRequest):
        return "Dead"

Usage:

>>> driver = webdriver.Firefox()
>>> get_status(driver)
'Alive'
>>> driver.quit()
>>> get_status(driver)
'Dead'

Another approach would be to make your custom Firefox webdriver and set the session_id to None in quit():

class MyFirefox(webdriver.Firefox):
    def quit(self):
        webdriver.Firefox.quit(self)
        self.session_id = None

Then, you can simply check the session_id value:

>>> driver = MyFirefox()
>>> print driver.session_id
u'69fe0923-0ba1-ee46-8293-2f849c932f43'
>>> driver.quit()
>>> print driver.session_id
None

Upvotes: 21

MervS
MervS

Reputation: 5902

How about executing a driver command and checking for an exception:

import httplib, socket

try:
    driver.quit()
except httplib.CannotSendRequest:
    print "Driver did not terminate"
except socket.error:
    print "Driver did not terminate"
else:
    print "Driver terminated"

Upvotes: 2

Related Questions