Selenium Wait Methods

Selenium convenience methods wait a specified amount of time for various elements or state of elements. It returns one of two states True, False or an exception is raised. These are convenience methods. You can use them or make your own version. If necessary, you can make custom methods. You can and should avoid using sleep statements to wait for DOM’s  to go into a state for testing. Elements come and go into into a DOM in a dynamic web page. The waits are intended to delay test processing until something happens in the DOM. Worst case an exception is thrown and you need to handle it to continue your test. If an Exception is thrown you can stop the test immediately or continue the test to find other potential faults.

The wait methods are very useful aids to validate quite a few test features.

The list of convenience methods is long. The list gets longer periodically. Most of the methods are straight forward to apply, others are not so obvious because of the analysis involved. You usually see the wait period is mandatory even if it’s zero . As an alternative test,  you can wait until the state is Not true with the until_not form, the negative test case may be useful for the specific test case.

Examples
WebDriverWait(driver, 10).until(EC.presence_of_element…
WebDriverWait(driver, 10).until_not(EC.presence_of_element…

The Title wait function validates the Title.

title_is(title)
Exact match of title, case sensitive 

title_contains(title fragment)
Contains text in title, case sensitive 

Check the title string

def wait_title():
    url = “http://www.google.com”
    driver = setup(url)
    title = “Google”
    try:
        WebDriverWait(driver, 10).until(EC.title_is(title))
        WebDriverWait(driver, 10).until(EC.title_contains(title))
        print(“Test passed !”)
    except TimeoutException:
        print(“Timeout exception raised title {} not available”.format(title))
    finally:
       driver.quit()

The methods any_of, all_of and none_of are convenience methods to validate a combination of states.

any_of(*expected_conditions)
An expectation that any of multiple expected conditions is true. Equivalent to a logical ‘OR’.  Returns results of
the first matching condition, or False if none do.

all_of(*expected_conditions) 
An expectation that all of multiple expected conditions is True. Equivalent to a logical ‘AND’.   Returns: When any ExpectedCondition
is not met: False. When all ExpectedConditions
are met: A List with each ExpectedCondition’s return value.

none_of(*expected_conditions) 
An expectation that none of 1 or multiple expected conditions is true. Equivalent to a logical  ‘NOT-OR’.
Returns a Boolean T or F. Any Pass even one. all pass

def wait_any_combinations():
    url = “http://www.google.com”
    driver = setup(url)
# the test reference Xpath sample //a[normalize-space()=’Gmail’]
    try:
        WebDriverWait(driver, 10).until(
                     EC.any_of(
# any_of is a big OR statement
# the first two tests are intentionally False
                     EC.element_to_be_clickable((By.XPATH, ‘//button/div[contains(text(), “Anybody”)]’)),
                     EC.element_to_be_clickable((By.XPATH, ‘//span/div[contains(text(), “Somebody”)]’)),
# must be clickable, must be an anchor and must contain the string Gmail
                    EC.element_to_be_clickable((By.XPATH, ‘//a[contains(text(), “Gmail”)]’))
                    ))
        WebDriverWait(driver, 10).until(
                      EC.none_of(
# All intentionally False
                        EC.element_to_be_clickable((By.XPATH, ‘//button/div[contains(text(), “Anybody”)]’)),
                        EC.element_to_be_clickable((By.XPATH, ‘//span/div[contains(text(), “Somebody”)]’)),
                   ))
       WebDriverWait(driver, 10).until(
                        EC.all_of(
# True must be clickable + must be an anchor +  must contain the string Gmail
                         EC.element_to_be_clickable((By.XPATH, ‘//a[contains(text(), “Gmail”)]’))
                  ))
            print(“Test passed !”)
     except TimeoutException:
            print(“Timeout exception no match found”)
     finally:
            driver.quit()

 

Visibility Testing

Visible means the element has dimensions which could be used to display the image element on the screen. A visible element contains an absolute X/Y reference location and a size with a height and width
location {‘x’: 296, ‘y’: 150}
size {‘height’: 200, ‘width’: 500}
A visible element may be hidden.
There is no such thing as a blank space around an element. Each element has a location and area, even though there may be white space, that area is accounted for.

visibility_of
An element, known to be present on the DOM of a page, is visible.
Visibility means that the element is not only
displayed but also has a height and width that greater than 0.

visibility_of_element_located
An expectation for checking that an element is present on the DOM of a page and visible.
Visibility means that the element is not only displayed but also has a height and width
that is greater than 0. locator – used to find the element returns the WebElement once
it is located and visible

visibility_of_any_elements_located(locator):
Notice the s in elements. At least one element visible on a web page.
locator is used to find the element returns the list of WebElements once they are located

visibility_of_all_elements_located(locator):
Again looking for elements, returns a list. An expectation for checking that all elements are present on the DOM of a page and
visible. Again,
Visible as previously defined.

def wait_visible():
    url = “http://www.google.com”
    driver = setup(url)
    class_name = “pHiOh” # six instances
    about = driver.find_element(By.LINK_TEXT, ‘About’)
    try:
        WebDriverWait(driver, 10).until(EC.visibility_of(about)),
        WebDriverWait(driver,10).until(EC.visibility_of_element_located((By.LINK_TEXT, ‘About’)))
# notice the s in elements
      elements = WebDriverWait(driver, 10).until(EC.visibility_of_any_elements_located((By.CLASS_NAME, class_name)))
# Returns classes at the following six locations
# these are six text strings at the bottom of google.com
# {‘x’: 155, ‘y’: 923} {‘x’: 254, ‘y’: 923}
# {‘x’: 341, ‘y’: 923}{‘x’: 440, ‘y’: 876}
# {‘x’: 713, ‘y’: 923} {‘x’: 789, ‘y’: 923}
         elements = WebDriverWait(driver, 10).until(EC.visibility_of_all_elements_located((By.CLASS_NAME, class_name)))
         print(“Found {} versions of class {}”.format(len(elements),class_name))
    except TimeoutException:
        print(“Timeout exception element not visible”)
    finally:
       driver.quit()

If it’s not visible, it’s invisible. No location, no X,Y dimensions. If it doesn’t have a location, it’s not going to have an area. 

invisibility_of_element_located(locator)
A locator reference that’s invisible and/or not present on the DOM.

invisibility_of_element(element)
An element reference that’s invisible and/or not present on the DOM.

new_window_is_opened(current_handles):
An expectation that a new window will be opened and have the number of windows handles increase

presence_of_all_elements_located(locator)
An expectation for checking that there is at least one element present on a web page.
locator is used to find the element returns the list of WebElements once they are located                 
presence_of_element_located (locator)
An expectation for checking that an element is present on the DOM of a page. This does
not necessarily
mean that the element is visible. locator – used to find the element
returns the WebElement once it is located

Elements have embedded text values. A bit of a departure from elements with a specific meaning to the DOM. 

text_to_be_present_in_element(locator, text)
An expectation for checking if the given text is present in the specified element.

text_to_be_present_in_element_value(locator, text)
An expectation for checking if the given text is present in the specified element.

frame_to_be_available_and_switch_to_it(locator)
Two parts, checks whether a given frame is available to switch to. If so it switches
the given driver to the specified frame.
<FRAMESET>…<FRAME></FRAME>…</FRAMESET> Embedded as deeply as required
Frames are deprecated in HTML5  “https://html.com/frames/#The_Difference_Between_Frames_and_Iframes” 

Select Web elements are hard to test. You shouldn’t go out on your own when very
good code have been implemented and supplied by the community.

<select>
<option value=value1>Bread</option>
<option value=value2 selected>Milk</option>
<option value=value3>Cheese</option>
</select>

element_to_be_selected(element)
Check the selection is selected element

element_located_to_be_selected(locator)
An expectation for the element to be located is selected. locator is a tuple of (by, path)

element_selection_state_to_be(element, is_selected)
An expectation for checking if the given element is selected. element is WebElement
object is_selected is a Boolean.”

element_located_selection_state_to_be(locator, is_selected)
The element to be located is selected. locator is a tuple of (by, path)

element_to_be_clickable(locator)
An Expectation for checking an element is visible, enabled and clickable.                            

staleness_of(element)
Wait until item is gone from the Dom. If it doesn’t return False. Any element that isn’t part of the DOM is considered stale obviously a big universe

Extra Windows

alert_is_present()
Indicates an alert has been fired

new_window_is_opened( current handles)
An expectation that a new window will be opened and have the number of windows
handles increase. Often related to an alert

number_of_windows_to_be( num_windows)
An expectation for the number of windows to be a certain value. Often related to a new alert

URL testing 

A web page may be reached at a static or dynamic location. A static address is self explanatory, a fixed URL and the most common way to reach a web site.  A dynamic URL is web page created on the fly for a specific purpose or customer. Typically the general template is the same among the instances, but the information presented is customized.

Your Selenium Test Project may include a step to type in a customer name in the original web page. You would be redirected to another web page generated on the fly. Your test would then would want to validate the URL of the freshly generated web page. You may want to wait between entering a customer name in a static web page until the dynamic page appears. Your test will not know the URL has changed.  Your test case should require a URL check. You may not know the exact URL so there are tests below for a sub string match.

url_* methods. These four methods search for sub-strings or an exact match in the URL’s. Returns True or False.

url_changes
Url is the expected url, which must not be an exact match returns True if the url is different, false otherwise.

url_contains
Url contains a case-sensitive substring. Returns True when the url matches, False otherwise

url_to_be
The current url. is an exact match. Returns True if the url matches, False otherwise.
The method waits a total time, checking every 500 MS to see if the correct change has
appeared and immediately returns True. If the match isn’t made it throws an exception??

url_matches 
The current url. pattern is the expected pattern, which must be an exact match returns True if the url matches, False otherwise.

Simulating waiting for an URL for ten seconds, not found and throwing a timeout exception. 

def wait_two():
    url = "http://www.google.com"
    driver = setup(url)
    fake_url = "http://www.notgoogle.com"
    try:
        WebDriverWait(driver, 10).until(EC.url_to_be(fake_url))
    except TimeoutException:
        print("Timeout exception raised URL {} not available".format(fake_url))
    finally:
        driver.quit()