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

0sgqnhkj  于 2022-11-29  发布在  Python
关注(0)|答案(9)|浏览(241)

我想控制WebDriver是否退出,但找不到相应的方法。(It seems that in Java there's a way to do it

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

我还研究了WebDriver的属性,但找不到任何特定的方法来获取驱动程序状态的信息。

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

tsm1rwdh1#

如果您要研究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()被调用。
换句话说,您需要进行外部调用来检查 * status *:

>>> 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 web驱动程序 *,并在quit()中将session_id设置为None

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
dfuffjeb

dfuffjeb2#

我遇到了同样的问题,并试图返回标题-这对我使用Chromedriver有效...

from selenium.common.exceptions import WebDriverException

try:
    driver.title
    print(True)
except WebDriverException:
    print(False)
3qpi33ja

3qpi33ja3#

以上建议的方法在Selenium版本3.141.0上不起作用

dir(driver.service) found a few useful options 

driver.session_id   
driver.service.process
driver.service.assert_process_still_running()
driver.service.assert_process_still_running

当我在关闭一个已经关闭的驱动程序时遇到问题时,我发现了这个问题,在我的例子中,一个围绕驱动程序的try catch。close()对我的目的很有效。

try:
    driver.close()
    print("driver successfully closed.")
except Exception as e:
    print("driver already closed.")

同时:

import selenium
help(selenium)

检查Selenium版本号

wooyq4lh

wooyq4lh4#

这对我的工作:

from selenium import webdriver

driver = webdriver.Chrome()
print( driver.service.is_connectable()) # print True

driver.quit()
print( driver.service.is_connectable()) # print False
ffdz8vbo

ffdz8vbo5#

如何执行驱动程序命令并检查异常:

import httplib, socket

try:
    driver.quit()
except httplib.CannotSendRequest:
    print "Driver did not terminate"
except socket.error:
    print "Driver did not terminate"
else:
    print "Driver terminated"
vcirk6k6

vcirk6k66#

它在java中工作,在FF上检查

((RemoteWebDriver)driver).getSessionId() == null
gcuhipw9

gcuhipw97#

有这样的功能:
如果驱动程序.服务.是可连接的():print('可以进行')

2fjabf4q

2fjabf4q8#

在我的例子中,我需要检测浏览器界面是否关闭-不管- chromedriver的状态。因此,这里的答案都不起作用,我只是决定去显而易见的:

from selenium.common.exceptions import WebDriverException

try:
    driver.current_url
    print('Selenium is running')
except WebDriverException:
    print('Selenium was closed')

虽然这是一个有点黑客,它已经达到了我的目的完美。

rks48beu

rks48beu9#

“”“Python定义关闭驱动程序():global drivername drivername.quit()global driveron driveron=False“''这个函数“closedriver”使用了一个名为“drivername”的全局变量和一个名为“driveron”的全局布尔变量,您可以只传递当前驱动程序作为参数,但是
注意:driveron必须是全局的,才能存储驱动程序的状态为“on”或“off”。''' python
定义关闭驱动程序(驱动程序名称):
全局驱动程序on
尝试:
驱动程序名称.quit()
但以下情况除外:
通过
driveron=假
''''
当你启动一个新的驱动程序时,只需使用一个
全局驱动程序on
如果驱动程序未打开:
驱动程序=网页驱动程序.Chrome()

相关问题