Python Selenium: How to check whether the WebDriver did quit()?

前端 未结 7 971
一个人的身影
一个人的身影 2021-02-08 12:26

I want to control whether my WebDriver quit but I can\'t find a method for that. (It seems that in Java there\'s a way to do it)

from selenium impor         


        
相关标签:
7条回答
  • 2021-02-08 12:49

    I ran into the same problem and tried returning the title - this worked for me using chromedriver...

    from selenium.common.exceptions import WebDriverException
    
    try:
        driver.title
        print(True)
    except WebDriverException:
        print(False)
    
    0 讨论(0)
  • 2021-02-08 12:51

    How about executing a driver command and checking for an exception:

    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"
    
    0 讨论(0)
  • suggested methods above didn't work for me on selenium version 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 
    

    I found this SO question when I had a problem with closing an already closed driver, in my case a try catch around the driver.close() worked for my purposes.

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

    also:

    import selenium
    help(selenium)
    

    to check selenium version number

    0 讨论(0)
  • 2021-02-08 12:55

    There is this function:

    if driver.service.isconnectible(): print('Good to go')

    0 讨论(0)
  • 2021-02-08 13:00

    it works in java, checked on FF

    ((RemoteWebDriver)driver).getSessionId() == null
    
    0 讨论(0)
  • 2021-02-08 13:07

    If you would explore the source code of the python-selenium driver, you would see what the quit() method of the firefox driver is doing:

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

    There are things you can rely on here: checking for the profile.path to exist or checking the binary.process status. It could work, but you can also see that there are only "external calls" and there is nothing changing on the python-side that would help you indicate that quit() was called.

    In other words, you need to make an external call to check the 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
    

    You can put it under the try/except and make a reusable function:

    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"
    

    Usage:

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

    Another approach would be to make your custom Firefox webdriver and set the session_id to None in quit():

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

    Then, you can simply check the session_id value:

    >>> driver = MyFirefox()
    >>> print driver.session_id
    u'69fe0923-0ba1-ee46-8293-2f849c932f43'
    >>> driver.quit()
    >>> print driver.session_id
    None
    
    0 讨论(0)
提交回复
热议问题