【问题标题】:Python Selenium: How to check whether the WebDriver did quit()?Python Selenium:如何检查 WebDriver 是否退出()?
【发布时间】:2015-03-09 02:47:07
【问题描述】:

我想控制我的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 的属性,但我找不到任何特定的方法来获取有关驱动程序状态的信息。同时检查会话ID:

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

【问题讨论】:

    标签: python selenium selenium-webdriver


    【解决方案1】:

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

    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 网络驱动程序,并将 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
    

    【讨论】:

    • 在“生产质量”代码中是否需要检查驱动程序终止?换句话说,我如何平衡真正的防弹代码与运行所有这些检查所需的时间?
    • @franklin 我自己在使用 selenium 时实际上从未做过浏览器终止检查,我认为 OP 在这里只是有一个特定的用例。不确定退出驱动程序后是否真的需要运行。你怎么看?
    • 我很感兴趣,我实际上在这里asked the question。老实说,我认为用任何语言解构对象的失败率非常低,没有必要进行测试。
    【解决方案2】:

    这对我有用:

    from selenium import webdriver
    
    driver = webdriver.Chrome()
    print( driver.service.is_connectable()) # print True
    
    driver.quit()
    print( driver.service.is_connectable()) # print False
    

    【讨论】:

      【解决方案3】:

      上述建议的方法在 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 
      

      当我在关闭一个已经关闭的驱动程序时遇到问题时,我发现了这个 SO 问题,在我的情况下,围绕 driver.close() 的 try catch 可以满足我的目的。

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

      还有:

      import selenium
      help(selenium)
      

      查看 selenium 版本号

      【讨论】:

        【解决方案4】:

        我遇到了同样的问题并尝试返回标题 - 这对我使用 chromedriver...

        from selenium.common.exceptions import WebDriverException
        
        try:
            driver.title
            print(True)
        except WebDriverException:
            print(False)
        

        【讨论】:

        • 如果您使用它来确定驱动程序是否仍然“活动”,则它仅在您已经加载网站时才有效。新驱动程序将准备好接受命令,但仍会在此处打印 False。
        【解决方案5】:

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

        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"
        

        【讨论】:

          【解决方案6】:

          ''''蟒蛇 定义关闭驱动程序(): 全局驱动程序名 drivername.quit() 全球驱动 驱动=假 '''' 此函数“closedriver”使用名为“drivername”的全局变量和名为“driveron”的全局布尔变量,您可以将当前驱动程序作为参数传递,但是
          注意: driveron 必须是全局的,才能存储驱动程序的“开”或“关”状态。 ''''蟒蛇
          def closedriver(驱动程序名称):
          全局驱动
          试试:
          drivername.quit()
          除了:
          通过
          driveron=假
          ''''
          当您启动新驱动程序时,只需使用检查
          全局驱动
          如果不是驱动程序:
          driver=webdriver.Chrome()

          【讨论】:

          • 欢迎来到 StackOverflow。虽然这段代码可以解决问题,including an explanation 解决问题的方式和原因确实有助于提高帖子的质量,并可能导致更多的赞成票。请记住,您正在为将来的读者回答问题,而不仅仅是现在提出问题的人。请edit您的答案添加解释并说明适用的限制和假设。
          • 请尽量包含一些关于您的解决方案的解释。这有助于其他人了解您的方法。
          【解决方案7】:

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

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

          【讨论】:

            【解决方案8】:

            有这个功能:

            如果 driver.service.isconnectible(): print('准备好了')

            【讨论】:

              【解决方案9】:

              对于这里大多数人的方法,浏览器界面本身以及chromedriver.exe(或等效)都需要关闭;否则,Selenium 认为它运行正常。无论chromedriver是否仍在运行,我都需要检测浏览器界面是否关闭。在这里尝试了一堆答案后,我选择了显而易见的:

              from selenium.common.exceptions import WebDriverException
              
              try:
                  driver.current_url
                  print('Selenium is running')
              except WebDriverException:
                  print('Selenium was closed')
              

              而且它工作得很好,比这里的大多数答案对我的目的都好。

              【讨论】:

                猜你喜欢
                • 2018-03-19
                • 2013-09-08
                • 2013-01-04
                • 2018-07-20
                • 1970-01-01
                • 1970-01-01
                • 2014-09-23
                • 1970-01-01
                • 2017-02-26
                相关资源
                最近更新 更多