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

9

18

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'
Hamlet answered 9/3, 2015 at 2:47 Comment(0)
C
21

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
Clutter answered 9/3, 2015 at 3:4 Comment(3)
Is checking for driver termination necessary in "production quality" code? In other words, how do I balance really bullet proof code versus the time it takes to run all these checks?Nailhead
@Nailhead I've actually never done browser termination checks while using selenium myself and I think the OP just had a specific use case here. Not sure if this is really needed to run after quitting the driver. What do you think?Clutter
I was so interested, I actually asked the question here. I honestly think that the failure rate of deconstructing an object in any language is so low that it isn't necessary to test.Nailhead
V
14

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)
Vada answered 2/10, 2017 at 19:52 Comment(1)
If you are using this to determine if a driver is still "alive", it will only work if you have already loaded a website. A new driver would be ready to accept commands, but still print False here.Kolb
R
8

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
Refund answered 3/8, 2021 at 13:44 Comment(3)
This simple solution still works well on 2023-4-17. Other answers below this question were more or less outdated or getting to complicated. By the way, driver.service.is_connectable() is synchronized.Caryophyllaceous
Works perfectly when you do driver.quit(). But i was kinda surprised that it still shows True after I do driver.close() for a single browser tab, so no running Chrome processes left. Hmm, how it's connectable if browser in not running? Tried this on Ubuntu 22.04 Server.Custody
I think the behaviour you mantioned is because the difference between the methods close() and quit(). While close() closes window/tab without ending session, quit() ends WebDriver session ReferenceRefund
M
2

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"
Manic answered 9/3, 2015 at 3:20 Comment(0)
Z
2

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

Zincograph answered 18/11, 2020 at 3:11 Comment(0)
L
0

it works in java, checked on FF

((RemoteWebDriver)driver).getSessionId() == null
Landaulet answered 7/7, 2015 at 18:58 Comment(0)
E
0

There is this function:

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

Emerick answered 19/9, 2020 at 21:9 Comment(0)
P
0

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.

Punner answered 14/2, 2022 at 17:58 Comment(0)
C
-2

''''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()

Charlena answered 12/12, 2020 at 13:38 Comment(3)
Welcome to StackOverflow. While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply.Slut
Please try to always include some explanation about your solution. This help others understand your approach.Nonbelligerent
This approach does not really answer the OP's question. Also, it appears you are using a global variable drivername to share the driver among parts of your code and a second global variable driveron to share the status of the latter. This is not necessary. As you can see from the other replys, you can just query the status of your driver directly by querying drivername.Commons

© 2022 - 2024 — McMap. All rights reserved.