Skip to content
Advertisement

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

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

Advertisement

Answer

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
Advertisement