Selenium displays wait

In the UI test automation, in order to maintain the stability of the cases, we tend to be set according to wait, show waiting to say clear until the occurrence of an element or elements of certain conditions, such as clickable, visible and other conditions, if within the stipulated time has not found, then will throw an Exception.

Here is a test case I wrote in Selenium that shows the use of the Display wait in Selenium, using the Expected_conditions module and the WebDriverWait class, Notice here that expected_conditions is the name of a PY file, which is the name of a module with a number of condition classes under it, and title_is is one of the condition classes used in our use case.

WebDriverWait is a class that checks to see if a condition has been met. The WebDriverWait class has only two methods: until until a condition is met and until_NOT until a condition is not met.

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

WebDriverWait has four parameters: driver driver, timeout timeout time, poll_frequency= poll_frequency training time, which is the interval to determine whether the condition is satisfied. The default is 0.5 seconds. Ignored_exceptions =None The exceptions that need to be ignored while waiting are an iterable set of exception classes, for example, a list, It is [NoSuchElementException, NoSuchAttributeException, InvalidElementStateException…]. , by default, is a tuple containing only one NoSuchElementException, because the condition can only be determined if the element is present. NoSuchElementException must occur in the course of continuous rotation, and must be ignored at this time. Otherwise the program will break.

Driver and timeout are positional parameters to be passed, and the other two are keyword parameters to be passed. If they are not passed, they have specified default values.

Let’s move on to today’s topic, a discussion of wait conditions in Selenium

Waiting on the condition

The implementation principle of conditional classes

In selenium. Webdriver. Support. Expected_conditions this module, the storage conditions, all waiting for each condition class structure is the same a __init__ constructor and a __call__ method.

In Python, if you want to use an object of type as a function, you can implement a __call__ method for the 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()
Copy the code

The case() object will execute the logic in the __call__ method to print the title of the current page. We take an implementation class of Selenium:

class presence_of_element_located(object) :

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

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

The meaning of this condition class is to judge whether an element is rendered to the page, in the use of the conditions need to be instantiated, incoming element positioning, then to determine the need to call and afferent driver instance objects, for instance objects call will be executed when the conditional logic in the __call__ method.

WebDriverWaitHow is the conditional judgment made

Going back to the beginning of the article, let’s look at the code we used to display wait:

wait = WebDriverWait(self.driver, 2)
wait.until(EC.title_is('Just Google it and you'll know.'))
Copy the code

Instantiate a WebDriverWait object, then call the until method and pass an instance of the condition. The until method is constantly checked to see if 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)
Copy the code

The method argument is the instance object of the condition we passed in, value = method(self._driver) where the object is called, which executes the logic in the __call__ method.

What are the conditions in Selenium

  • Title_is Checks whether the title is present
  • 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 does not mean it is visible
  • Url_contains Determines whether the current URL contains a URL
  • Url_matches Checks whether the current URL matches a certain format
  • Url_to_be Determines whether the current URL appears
  • Url_changes Determines whether the current URL has changed
  • Visibility_of_element_located determines whether an element has been added to the DOM tree and is greater than 0 in width and height
  • 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 if all elements are visible on the page
  • Text_to_be_present_in_element determines whether the specified element contains the expected string
  • Text_to_be_present_in_element_value Determines whether the expected string is contained in the specified element attribute value
  • Frame_to_be_available_and_switch_to_it Checks whether iframe can be switched in
  • Invisibility_of_element_located determines if an element is not visible in the DOM
  • Element_to_be_clickable determines whether an element is visible and enabled, that is, clickable
  • Staleness_of waits for an element to be deleted from the DOM
  • Element_to_be_selected Determines whether an element is selected. Used in drop-down lists
  • Element_located_to_be_selected means the same as above, except that the above instantiation passes in the element object, and this one passes in the location
  • Element_selection_state_to_be determines whether the selected state of an element is as expected
  • Element_located_selection_state_to_be is the same as above, except that the value is passed differently
  • Number_of_windows_to_be Determines whether the current number of Windows is the expected number
  • New_window_is_opened Checks whether a window is added
  • Alert_is_present Checks whether a pop-up window exists on the page

Those are all the conditions supported by Selenium.

Then there’s customization

So with all this talk about conditions, we could actually implement a condition class 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
Copy the code

The url and title of the page are used to determine whether the page is loaded correctly.

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("Just Google it and you'll know."."http://www.baidu.com/"))
Copy the code