小编典典

Python Selenium:如何检查WebDriver是否已退出()?

selenium

我想控制是否WebDriver退出,但是找不到解决方法。

from selenium import webdriver
driver = webdriver.Firefox()
driver.quit()
driver # <selenium.webdriver.firefox.webdriver.WebDriver object at 0x108424850>
driver is None # False

我还探讨了的属性,WebDriver但是找不到任何特定的方法来获取有关驱动程序状态的信息。还要检查会话ID:

driver.session_id # u'7c171019-b24d-5a4d-84ef-9612856af71b'

阅读 1555

收藏
2020-06-26

共1个答案

小编典典

如果您探索python-
selenium驱动程序的源代码,则将看到firefox驱动程序的quit()方法在做什么:

def quit(self):
    """Quits the driver and close every associated window."""
    try:
        RemoteWebDriver.quit(self)
    except (http_client.BadStatusLine, socket.error):
        # Happens if Firefox shutsdown before we've read the response from
        # the socket.
        pass
    self.binary.kill()
    try:
        shutil.rmtree(self.profile.path)
        if self.profile.tempfolder is not None:
            shutil.rmtree(self.profile.tempfolder)
    except Exception as e:
        print(str(e))

您可以在此处依赖某些内容:检查是否profile.path存在或检查binary.process状态。它可以工作,但是您还可以看到只有“外部调用”,并且
在python端没有任何改变 可以帮助您表明quit()已调用了它。

换句话说,您需要拨打外部电话以检查 状态

>>> from selenium.webdriver.remote.command import Command
>>> driver.execute(Command.STATUS)
{u'status': 0, u'name': u'getStatus', u'value': {u'os': {u'version': u'unknown', u'arch': u'x86_64', u'name': u'Darwin'}, u'build': {u'time': u'unknown', u'version': u'unknown', u'revision': u'unknown'}}}
>>> driver.quit()
>>> driver.execute(Command.STATUS)
Traceback (most recent call last):
...
socket.error: [Errno 61] Connection refused

您可以将其放在下方try/except并使其可重用:

import httplib
import socket

from selenium.webdriver.remote.command import Command

def get_status(driver):
    try:
        driver.execute(Command.STATUS)
        return "Alive"
    except (socket.error, httplib.CannotSendRequest):
        return "Dead"

用法:

>>> driver = webdriver.Firefox()
>>> get_status(driver)
'Alive'
>>> driver.quit()
>>> get_status(driver)
'Dead'

另一种方法是 制作自定义Firefox Webdriver 并将设置session_idNonein quit()

class MyFirefox(webdriver.Firefox):
    def quit(self):
        webdriver.Firefox.quit(self)
        self.session_id = None

然后,您可以简单地检查session_id值:

>>> driver = MyFirefox()
>>> print driver.session_id
u'69fe0923-0ba1-ee46-8293-2f849c932f43'
>>> driver.quit()
>>> print driver.session_id
None
2020-06-26