【问题标题】:Python Selenium Detect when the browser is closedPython Selenium 在浏览器关闭时检测
【发布时间】:2018-08-04 11:56:05
【问题描述】:

现在,我用它来检测用户何时关闭浏览器:

while True:
    try:
        # do stuff
    except WebDriverException:
        print 'User closed the browser'
        exit()

但我发现这是非常不可靠且非常糟糕的解决方案,因为WebDriverException 捕获了很多异常(如果不是全部),其中大多数不是由于用户关闭浏览器造成的。

我的问题是:如何检测用户何时关闭浏览器?

【问题讨论】:

  • 您可以使用浏览器无法访问异常。 seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/…
  • 嗨,对不起,我误解了异常在所有绑定中都很常见,我们在 Ruby Selenium 绑定中使用Selenium::WebDriver::Error::NoSuchWindowError,所以我建议你!好的,你可以搜索对应的 Exception for Python Binding。
  • @cruisepandey 此讨论可能无济于事,因为此处浏览器将由用户的操作关闭,而不是通过调用driver.quit()
  • @CoreyGoldberg 我可以确认这不起作用。事实上,当用户手动关闭浏览器时,浏览器对象的所有属性似乎都没有改变。我试图抓住它,以便我可以以编程方式重新打开浏览器,但我已经放弃了。 “如果关闭浏览器会怎样?”就像“如果你拔掉电脑上的插头会发生什么?”或者“如果你把键盘敲到显示器上会发生什么?”您无法在软件中防范它。

标签: python selenium selenium-webdriver exit


【解决方案1】:

我建议使用:

>>> driver.get_log('driver')
[{'level': 'WARNING', 'message': 'Unable to evaluate script: disconnected: not connected to DevTools\n', 'timestamp': 1535095164185}]

因为每当用户关闭浏览器窗口时驱动程序都会记录这一点,这似乎是最 Pythonic 的解决方案。

所以你可以这样做:

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)

如果您有兴趣,可以查找文档here

我正在使用 chromedriver 2.41 和 Chrome 68。

【讨论】:

  • 非常有帮助的答案
【解决方案2】:

类似于 Federico Rubbis 的回答,这对我有用:

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

可能不是一个跨 selenium 版本稳定的解决方案。
编辑:从不同环境运行甚至不稳定。丑陋的修复:使用BaseException 而不是selenium.common.exceptions.InvalidSessionIdException

【讨论】:

    猜你喜欢
    • 2013-05-12
    • 1970-01-01
    • 2019-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-21
    • 1970-01-01
    相关资源
    最近更新 更多