2017-10-07 66 views
0

下面是示例代碼:在Python中,如何檢查Selenium WebDriver是否退出?

from selenium import webdriver 

driver = webdriver.Firefox() 

(該窗口被關閉,由於這裏的一些原因)

driver.quit() 

回溯(最近通話最後一個):文件 「」,1號線, in 文件 「/usr/local/lib/python2.7/dist-packages/selenium/webdriver/firefox/webdriver.py」, line 183,in quit RemoteWebDriver.quit(self)File「/ usr/local /lib/python2.7/dist-packages/selenium/webdriv er/remote/webdriver.py「, line 592,in quit self.execute(Command.QUIT)File」/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「, line 194,in check_response 提高exception_class(消息,屏幕,堆棧跟蹤)selenium.common.exceptions.WebDriverException:消息:試圖運行 命令沒有建立連接

是否有某種方式來檢查的webdriver的實例是活性?

回答

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") 
相關問題