Display waiting for selenium automated testing

Table of contents

waiting condition

The realization principle of the conditional class

How does WebDriverWait judge conditions

What are the conditions in selenium

Then it's custom

 Summarize:


When conducting UI automation testing, in order to maintain the stability of the use case, we often need to set the display wait. The display wait means that we must wait until an element appears or certain conditions of the element appear, such as clickable, visible, etc. , if none are found within the specified time, then it will be thrown Exception.

The above is a test case I seleniumwrote, which shows seleniumhow to use the display wait, which will use expected_conditionsmodules and WebDriverWaitclasses. Note that this expected_conditionsis the file name of a py file, which is a module name. There are many conditions under this module class, and what we use in our use case title_isis a conditional class.

WebDriverWaitIt is a class, and the function of this class is to constantly check whether the condition is met according to certain conditions. WebDriverWaitThe class has only two methods, one is untiluntil a certain condition is met and the other is until_notuntil a certain condition is not met.

class WebDriverWait(object):
    def __init__(self, driver, timeout, poll_frequency=POLL_FREQUENCY, ignored_exceptions=None):

WebDriverWaitThere are four parameters: driverdriver,  timeouttimeout time,  poll_frequency=POLL_FREQUENCYand training time, that is, the time interval for judging whether the conditions are met. The default is 0.5 seconds.  ignored_exceptions=NoneThe exceptions that need to be ignored during the waiting process are an iterable collection of exceptions. For example, we can set a list, which is [NoSuchElementException,NoSuchAttributeException,InvalidElementStateException....], by default, a tuple, which contains only one NoSuchElementException, because only when the element appears, can we judge whether the condition is satisfied. In the process of continuous training, it will definitely happen NoSuchElementException. At this time, it must be ignored. Drop this exception, otherwise the program will be interrupted.

Among them driver, and timeoutare the positional parameters of Bi Chuan, and the other two are keyword parameters that are selected to be passed. If they are not passed, they will have specified default values.

Let's enter our topic today, the discussion of waiting conditions in selenium

waiting condition

The realization principle of the conditional class

In selenium.webdriver.support.expected_conditionsthis module, all waiting conditions are stored, and the structure of each condition class is the same as a __init__construction method and a __call__method.

In python, if you want to use a type of object as a function, you can implement __call__methods for this class, as follows:

class TestCase:
    def __init__(self):
        self.driver = webdriver.Chrome(executable_path="./driver/chromedriver")
        self.driver.get('http://www.baidu.com')
        # sleep(2)

    def __call__(self):
        print(self.driver.title)

if __name__ == '__main__':
    case = TestCase()
    case()

case()The call of the object will execute __call__the logic in the method to print the title of the current page. We take a selenium implementation class:

class presence_of_element_located(object):

    def __init__(self, locator):
        self.locator = locator

    def __call__(self, driver):
        return _find_element(driver, self.locator)

The meaning of this condition class is to judge whether an element has been rendered to the page. When using this condition, it needs to be instantiated first, and the positioning of the element is passed in. Then, when the judgment is made, the instance object needs to be called and passed in. driverFor When the instance object calls, it will execute __call__the conditional judgment logic in the method.

WebDriverWaitHow to judge the condition

Go back to the beginning of the article and take a look at the code we use to display the wait:

wait = WebDriverWait(self.driver, 2)
wait.until(EC.title_is('百度一下,你就知道'))

First instantiate an WebDriverWaitobject, then call untilthe method and pass a conditional instance object, and untilthe method will continuously train whether the condition is met.

def until(self, method, message=''):
    screen = None
    stacktrace = None

    end_time = time.time() + self._timeout
    while True:
        try:
            value = method(self._driver)
            if value:
                return value
        except self._ignored_exceptions as exc:
            screen = getattr(exc, 'screen', None)
            stacktrace = getattr(exc, 'stacktrace', None)
        time.sleep(self._poll)
        if time.time() > end_time:
            break
    raise TimeoutException(message, screen, stacktrace)

methodThis parameter is the instance object of the condition we passed in, value = method(self._driver)here is to call the object, that is, to execute __call__the logic in the method.

What are the conditions in selenium

  • title_is to determine whether the title appears
  • title_contains determines whether the title page title contains certain characters
  • presence_of_element_located determines whether an element is loaded into the dom tree, but it does not mean that the element is visible
  • url_contains determines whether the current url contains a certain url
  • url_matches to determine whether the current url conforms to a certain format
  • url_to_be Determine whether the current url appears
  • url_changes Determine whether the current url has changed
  • visibility_of_element_located determines whether an element has been added to the dom tree, and the width and height are greater than 0
  • visibility_of determines whether an element is visible
  • presence_of_all_elements_located determines that at least one element exists in the dom tree and returns all located elements
  • visibility_of_any_elements_located determines that at least one element is visible on the page
  • visibility_of_all_elements_located determines whether all elements are visible on the page
  • text_to_be_present_in_element determines whether the expected string is contained in the specified element
  • text_to_be_present_in_element_value Determines whether the specified element attribute value contains the expected string
  • frame_to_be_available_and_switch_to_it determines whether the iframe can be switched in
  • invisibility_of_element_located determines whether an element is invisible in the dom
  • element_to_be_clickable determines whether an element is visible and enabled, that is to say, whether it can be clicked
  • staleness_of waits for an element to be removed from the dom
  • element_to_be_selected determines whether an element is selected, generally used in drop-down lists
  • element_located_to_be_selected has the same meaning as above, except that the element object is passed in when the above is instantiated, and this is the location
  • element_selection_state_to_be determines whether the selected state of an element meets expectations
  • element_located_selection_state_to_be is the same as above, but the value is different
  • number_of_windows_to_be determines whether the current number of windows is equal to the expected
  • new_window_is_opened to determine whether there is a window increase
  • alert_is_present Judge whether there is a pop-up window on the page

The above are all the conditions supported by selenium.

Then it's custom

Having said so many conditions, in fact, we can also implement a condition class by ourselves,

class page_is_load:
    
    def __init__(self, expected_title, expected_url):
        self.expected_title = expected_title
        self.expected_url = expected_url
    
    def __call__(self, driver):
        is_title_correct = driver.title == self.expected_title
        is_url_correct = driver.current_url == self.expected_url
        return is_title_correct and is_url_correct

The above is a conditional class implemented by myself, which judges whether the page is loaded correctly according to the url and title of the page.

class TestCase:
    def __init__(self):
        self.driver = webdriver.Chrome(executable_path="./driver/chromedriver")
        self.driver.get('http://www.baidu.com/')
        # sleep(2)

    def __call__(self):
        print(self.driver.title)

    def test_wait(self):
        wait = WebDriverWait(self.driver, 2)
        wait.until(page_is_load("百度一下,你就知道", "http://www.baidu.com/"))

Guess you like

Origin blog.csdn.net/MXB_1220/article/details/131690064