Although Federico Rubbi answer works, it doesn't work always. When the user closes the webdriver, the driver.get_log('driver')
will raise an excepton.
The following function works quite well, as far as i tested it (Chrome version 110). It also works with undetected chromedriver.
from selenium.webdriver.chrome.options import Options
from selenium import webdriver
from urllib3.exceptions import NewConnectionError, MaxRetryError
def is_driver_open(driver: webdriver.Chrome) -> bool:
"""
Checks if the webdriver is still open by checking the logs.
"""
disconnected_msg = 'Unable to evaluate script: disconnected: not connected to DevTools\n'
disc_msg = "Unable to evaluate script: no such window: target window already closed" \
"\nfrom unknown error: web view not found\n"
message_listener = "subscribing a listener to the already connected DevToolsClient"
if driver:
try:
log = driver.get_log('driver')
except (ConnectionRefusedError, MaxRetryError, NewConnectionError):
# The webdriver is closed, the connection to the Chrome is refused.
return False
print(f"is_driver_open(): log: {log}")
if len(log) != 0: # This does not catch all other messages.
if log[-1]['message'] in (disconnected_msg, disc_msg):
print("Webdriver is closed")
return False
elif message_listener in log[-1]['message']:
# It's not closed.
return True
else:
return True
else: # No errors, return True.
return True
if __name__ == "__main__":
options = Options()
driver = webdriver.Chrome(options=options)
print(f"Is driver open: {is_driver_open(driver)}")
driver.quit()
print(f"Is driver open: {is_driver_open(driver)}")
Selenium::WebDriver::Error::NoSuchWindowError
in Ruby Selenium Binding, So I suggested you! Okay you may search the corresponding Exception for Python Binding.driver.quit()
.