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

beq87vna  于 2023-01-05  发布在  Python
关注(0)|答案(5)|浏览(343)

下面是示例代码:

from selenium import webdriver

driver = webdriver.Firefox()

(The窗口由于某种原因关闭)

driver.quit()

Traceback (most recent call last): File "", line 1, in File "/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/webdriver/remote/webdriver.py", line 592, in quit self.execute(Command.QUIT) File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 297, in execute self.error_handler.check_response(response) File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/errorhandler.py", line 194, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.WebDriverException: Message: Tried to run command without establishing a connection

    • 是否有某种方法可以检查webdriver示例是否处于活动状态?**
vu8f3i0k

vu8f3i0k1#

是Python的...尝试退出并在失败时捕获异常。

try:
    driver.quit()
except WebDriverException:
    pass
u91tlkcl

u91tlkcl2#

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

hgqdbh6s3#

这是我想出来并喜欢的:

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)将抛出异常。

hgb9j2n6

hgb9j2n64#

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()
pcrecxhr

pcrecxhr5#

除了Corey Goldberg's answer,scign's answer之外:
不要忘记导入:

from selenium.common.exceptions import WebDriverException

此外,在Corey的回答中,代码将挂起大约10秒,同时试图关闭一个已经关闭的webdriver,然后再移动到except子句。

相关问题