Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Selenium Detect when the browser is closed

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?

like image 977
Programer Beginner Avatar asked Aug 04 '18 11:08

Programer Beginner


2 Answers

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.

like image 83
Federico Rubbi Avatar answered Sep 18 '22 13:09

Federico Rubbi


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 .

like image 41
dasWesen Avatar answered Sep 19 '22 13:09

dasWesen