![](/img/trans.png)
[英]Python Selenium: How to check whether the WebDriver did quit()?
[英]In Python, how to check if Selenium WebDriver has quit or not?
以下是示例代码:
from selenium import webdriver
driver = webdriver.Firefox()
(window 由于某种原因在这里被关闭)
driver.quit()
回溯(最近调用最后):文件“”,第 1 行,在文件“/usr/local/lib/python2.7/dist-packages/selenium/webdriver/firefox/webdriver.py”,第 183 行,退出 RemoteWebDriver .quit(self) 文件“/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py”,第 592 行,在退出 self.execute(Command.QUIT) 文件“/usr /local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py”,第297行,在执行self.error_handler.check_response(response)文件“/usr/local/lib/python2.7/ dist-packages/selenium/webdriver/remote/errorhandler.py”,第 194 行,在 check_response 中 raise exception_class(message, screen, stacktrace) selenium.common.exceptions.WebDriverException:消息:试图在不建立连接的情况下运行命令
有什么方法可以检查 webdriver 的实例是否处于活动状态?
成为 Pythonic... 如果失败,请尝试退出并捕获异常。
try:
driver.quit()
except WebDriverException:
pass
你可以使用这样的东西,它使用 psutil
from selenium import webdriver
import psutil
driver = webdriver.Firefox()
driver.get("http://tarunlalwani.com")
driver_process = psutil.Process(driver.service.process.pid)
if driver_process.is_running():
print ("driver is running")
firefox_process = driver_process.children()
if firefox_process:
firefox_process = firefox_process[0]
if firefox_process.is_running():
print("Firefox is still running, we can quit")
driver.quit()
else:
print("Firefox is dead, can't quit. Let's kill the driver")
firefox_process.kill()
else:
print("driver has died")
这是我发现并喜欢的:
def setup(self):
self.wd = webdriver.Firefox()
def teardown(self):
# self.wd.service.process == None if quit already.
if self.wd.service.process != None:
self.wd.quit()
注意:如果驱动程序已经退出, driver_process=psutil.Process(driver.service.process.pid)
将抛出异常。
Corey Golberg的答案是正确的方法。
但是,如果您真的需要深入了解,可以通过driver.service.process
属性访问管理打开浏览器的底层 Popen 对象。 如果进程已经退出, process
属性将为None
并且测试它是否为真将识别浏览器的状态:
from selenium import webdriver
driver = webdriver.Firefox()
# your code where the browser quits
if not driver.service.process:
print('Browser has quit unexpectedly')
if driver.service.process:
driver.quit()
除了Corey Goldberg 的回答,以及scign 的回答:
不要忘记导入:
from selenium.common.exceptions import WebDriverException
此外,在 Corey 的回答中,代码将在尝试关闭已经关闭的网络驱动程序时挂起大约 10 秒,然后再转到 except 子句。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.