在Python中,如何检查Selenium WebDriver是否已退出?

时间:2017-10-07 11:35:36

标签: python selenium

以下是示例代码:

from selenium import webdriver

driver = webdriver.Firefox()

(由于某种原因,窗口因此而关闭)

driver.quit()
  

Traceback(最近一次调用最后一次):文件“”,第1行,in      文件   “/usr/local/lib/python2.7/dist-packages/selenium/webdriver/firefox/webdriver.py”   第183行,退出       RemoteWebDriver.quit(self)File“/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的实例是否处于活动状态?

3 个答案:

答案 0 :(得分:2)

您可以使用类似于使用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")

答案 1 :(得分:1)

是Pythonic ...尝试退出并捕获异常,如果失败。

try:
    driver.quit()
except WebDriverException:
    pass

答案 2 :(得分:1)

这是我发现并喜欢的:

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)将引发异常。