gpt4 book ai didi

Python Selenium 在浏览器关闭时检测

转载 作者:太空狗 更新时间:2023-10-30 00:15:53 24 4
gpt4 key购买 nike

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

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

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

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

最佳答案

我建议使用:

>>> 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。

关于Python Selenium 在浏览器关闭时检测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51685330/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com