Right now, I use this as a way to detect when the user closes the browser:
while True:
try:
# do stuff
except WebDriverException:
print 'User closed the browser'
exit()
But I found out that it is very unreliable and a very bad solution since WebDriverException
catches a lot of exception (if not all) and most of them are not due to the user closing the browser.
My question is: How to detect when the user closes the browser?
I would suggest using:
>>> driver.get_log('driver')
[{'level': 'WARNING', 'message': 'Unable to evaluate script: disconnected: not connected to DevTools\n', 'timestamp': 1535095164185}]
since driver logs this whenever user closes browser window and this seems the most pythonic solution.
So you can do something like this:
DISCONNECTED_MSG = 'Unable to evaluate script: disconnected: not connected to DevTools\n'
while True:
if driver.get_log('driver')[-1]['message'] == DISCONNECTED_MSG:
print 'Browser window closed by user'
time.sleep(1)
If you're interested you can find documentation here.
I am using chromedriver 2.41 and Chrome 68.
Similar to Federico Rubbis answer, this worked for me:
import selenium
from selenium import webdriver
browser = webdriver.Firefox()
# Now wait if someone closes the window
while True:
try:
_ = browser.window_handles
except selenium.common.exceptions.InvalidSessionIdException as e:
break
time.sleep(1)
# ... Put code here to be executed when the window is closed
Probably not a solution that is stable across versions of selenium.
EDIT: Not even stable across running from different environments. Ugly fix: Use BaseException
instead of selenium.common.exceptions.InvalidSessionIdException
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With