Check if the browser opened with Selenium is still running (Python)

Question:

I want to check if a browser opened with Selenium is still open. I would need this check for closing a program. If the browser is not open, then the GUI should be destroyed without a message (tk.messagebox) coming. But if the browser is open, then the message should come as soon as the function is activated.
Here is the function:

def close():
    msg_box = tk.messagebox.askquestion('Exit Application', 'Are you sure you want to exit the application?',
                                        icon='warning')
    if msg_box == 'yes':
        root.destroy()
        try:
            web.close()
        except NameError:
            sys.exit(1)
        except InvalidSessionIdException:
            sys.exit(1)
        except WebDriverException:
            sys.exit(1)
    else:
        return
Asked By: JueK3y

||

Answers:

I don’t think there is a direct api for checking browser status. But you can use the the work around

def isBrowserAlive(driver):
   try:
      driver.current_url
      # or driver.title
      return True
   except:
      return False
Answered By: Trinh Phat

Unfortunately, there’s not a standardized way to check a driver’s status.

Here’s the most reliable cross-browser workaround that I’ve come up with over the years:

from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import WebDriverException

def is_webdriver_alive(driver):
    print('Checking whether the driver is alive')
    try:
        assert(driver.service.process.poll() == None) #Returns an int if dead and None if alive
        driver.service.assert_process_still_running() #Throws a WebDriverException if dead
        driver.find_element_by_tag_name('html') #Throws a NoSuchElementException if dead
        print('The driver appears to be alive')
        return True
    except (NoSuchElementException, WebDriverException, AssertionError):
        print('The driver appears to be dead')
        return False
    except Exception as ex:
        print('Encountered an unexpected exception type ({}) while checking the driver status'.format(type(ex)))
        return False

Usage:

driver_is_alive = is_webdriver_alive(driver)
Answered By: Pikamander2