Waits | Explicit wait

In the Previous Tutorial, we learned the following ways of handling synchronization issues –

  • What are the timeout/wait issues in Test Automation?
  • How to address it by waiting for the element before performing the action?
  • Getting the list of elements with a matching locator
  • Instructing code to wait for the predefined time – Hardcoded wait
  • Issues with the hardcoded wait and explore a sophisticated way to wait.

In this tutorial, we’ll –

  • Address the limitations of implicit wait
  • Explore explicit wait, a better mechanism provided by WebDriver API.

Limitations of Implicit Wait

Suppose, to handle timeout issues for an element we used implicit wait as described in the Previous Tutorial. It was working good as it waited reasonably long before performing each step. Suddenly the next statement failed to click on an element.

What could be the possible reason?

There could be plenty of reasons like the element does not exist or it got loaded on the page but it was not visible when the statement tried to click on it. So we need a way to make sure to wait until a “certain condition” is satisfied like “wait until the element is displayed”.

For these scenarios, we need Explicit Waits.

How to use Explicit Waits?

First, we need to instantiate WebDriverWait by passing it the driver object that we created before and also passing a timeout in seconds.

WebDriverWait wait = new WebDriverWait(driver, 60);

You need to import the package:

import org.openqa.selenium.support.ui.WebDriverWait;
#Pass a reference of WebDriver to the constructor of WebDriverWait
wait = WebDriverWait(driver, 60)

You need to import the package:

from selenium.webdriver.support.ui import WebDriverWait

Next, we can wait for expected conditions like this:

wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("login")));
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

#Wait until the username is displayed
wait.until(EC.element_to_be_visible(By.ID, 'login'))

In the above line of code, we are instructing WebDriver to wait until the element (whose id is login) is visible on the page. If the element is visible in the said duration it returns the element.

This is how we can use the returned element:

WebElement login = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("login")));
login.click();
#Wait until the username is displayed
login = wait.until(EC.element_to_be_visible(By.ID, 'login'))
login.click()

As we had already define the timeout (60 seconds) while creating the instance of WebDriverWait, if the element is not visible before the timeout the WebDriver will not wait any longer and will throw an Exception.

Expected Conditions

WebDriverWait is used in combination with expected conditions. Most of its methods are static. i.e. can be accessed without creating its object. It can be used in conjunctions with WebDriverWait in this format – wait.until(ExpectedConditions.nameOfTheMethod).

It provides methods for some conditions that we may expect in our tests.

Some of them are:

The ExpectedConditions class is under the package org.openqa.selenium.support.ui

titleIs

public static ExpectedCondition<java.lang.Boolean> titleIs(java.lang.String title)
An expectation for checking the title of a page.
Parameters:
title – the expected title, which must be an exact match
Returns:
true when the title matches, false otherwise

titleContains

public static ExpectedCondition<java.lang.Boolean> titleContains(java.lang.String title)
An expectation for checking that the title contains a case-sensitive substring
Parameters:
title – the fragment of title expected
Returns:
true when the title matches, false otherwise

urlToBe

public static ExpectedCondition<java.lang.Boolean> urlToBe(java.lang.String url)
An expectation for the URL of the current page to be a specific url.
Parameters:
url – the url that the page should be on
Returns:
true when the URL is what it should be

urlContains

public static ExpectedCondition<java.lang.Boolean> urlContains(java.lang.String fraction)
An expectation for the URL of the current page to contain specific text.
Parameters:
fraction – the fraction of the url that the page should be on
Returns:
true when the URL contains the text

urlMatches

public static ExpectedCondition<java.lang.Boolean> urlMatches(java.lang.String regex)
Expectation for the URL to match a specific regular expression
Parameters:
regex – the regular expression that the URL should match
Returns:
true if the URL matches the specified regular expression

presenceOfElementLocated

public static ExpectedCondition<WebElement> presenceOfElementLocated(By 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.
Parameters:
locator – used to find the element
Returns:
the WebElement once it is located

visibilityOfElementLocated

public static ExpectedCondition<WebElement> visibilityOfElementLocated(By locator)
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.
Parameters:
locator – used to find the element
Returns:
the WebElement once it is located and visible

visibilityOfAllElementsLocatedBy

public static ExpectedCondition<java.util.List<WebElement>> visibilityOfAllElementsLocatedBy(By locator)
An expectation for checking that all elements present on the web page that match the locator are visible. Visibility means that the elements are not only displayed but also have a height and width that is greater than 0.
Parameters:
locator – used to find the element
Returns:
the list of WebElements once they are located

visibilityOfAllElements

public static ExpectedCondition<java.util.List<WebElement>> visibilityOfAllElements(WebElement… elements)
An expectation for checking that all elements present on the web page that match the locator are visible. Visibility means that the elements are not only displayed but also have a height and width that is greater than 0.
Parameters:
elements – list of WebElements
Returns:
the list of WebElements once they are located

visibilityOfAllElements

public static ExpectedCondition<java.util.List<WebElement>> visibilityOfAllElements(java.util.List<WebElement> elements)
An expectation for checking that all elements present on the web page that match the locator are visible. Visibility means that the elements are not only displayed but also have a height and width that is greater than 0.
Parameters:
elements – list of WebElements
Returns:
the list of WebElements once they are located

visibilityOf

public static ExpectedCondition<WebElement> visibilityOf(WebElement element)
An expectation for checking that 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 is greater than 0.
Parameters:
element – the WebElement
Returns:
the (same) WebElement once it is visible

presenceOfAllElementsLocatedBy

public static ExpectedCondition<java.util.List<WebElement>> presenceOfAllElementsLocatedBy(By locator)
An expectation for checking that there is at least one element present on a web page.
Parameters:
locator – used to find the element
Returns:
the list of WebElements once they are located

textToBePresentInElement

public static ExpectedCondition<java.lang.Boolean> textToBePresentInElement(WebElement element,
java.lang.String text)
An expectation for checking if the given text is present in the specified element.
Parameters:
element – the WebElement
text – to be present in the element
Returns:
true once the element contains the given text

textToBePresentInElement

@Deprecated
public static ExpectedCondition<java.lang.Boolean> textToBePresentInElement(By locator,
java.lang.String text)
Deprecated. Use textToBePresentInElementLocated(By, String) instead
An expectation for checking if the given text is present in the element that matches the given locator.
Parameters:
locator – used to find the element
text – to be present in the element found by the locator
Returns:
the WebElement once it is located and visible

textToBePresentInElementLocated

public static ExpectedCondition<java.lang.Boolean> textToBePresentInElementLocated(By locator,
java.lang.String text)
An expectation for checking if the given text is present in the element that matches the given locator.
Parameters:
locator – used to find the element
text – to be present in the element found by the locator
Returns:
true once the first element located by locator contains the given text

textToBePresentInElementValue

public static ExpectedCondition<java.lang.Boolean> textToBePresentInElementValue(WebElement element,
java.lang.String text)
An expectation for checking if the given text is present in the specified elements value attribute.
Parameters:
element – the WebElement
text – to be present in the element’s value attribute
Returns:
true once the element’s value attribute contains the given text

textToBePresentInElementValue

public static ExpectedCondition<java.lang.Boolean> textToBePresentInElementValue(By locator,
java.lang.String text)
An expectation for checking if the given text is present in the specified elements value attribute.
Parameters:
locator – used to find the element
text – to be present in the value attribute of the element found by the locator
Returns:
true once the value attribute of the first element located by locator contains the given text

frameToBeAvailableAndSwitchToIt

public static ExpectedCondition<WebDriver> frameToBeAvailableAndSwitchToIt(java.lang.String frameLocator)
An expectation for checking whether the given frame is available to switch to.
If the frame is available it switches the given driver to the specified frame.

Parameters:
frameLocator – used to find the frame (id or name)
Returns:
WebDriver instance after frame has been switched

frameToBeAvailableAndSwitchToIt

public static ExpectedCondition<WebDriver> frameToBeAvailableAndSwitchToIt(By locator)
An expectation for checking whether the given frame is available to switch to.
If the frame is available it switches the given driver to the specified frame.

Parameters:
locator – used to find the frame
Returns:
WebDriver instance after frame has been switched

frameToBeAvailableAndSwitchToIt

public static ExpectedCondition<WebDriver> frameToBeAvailableAndSwitchToIt(int frameLocator)
An expectation for checking whether the given frame is available to switch to.
If the frame is available it switches the given driver to the specified frameIndex.

Parameters:
frameLocator – used to find the frame (index)
Returns:
WebDriver instance after frame has been switched

frameToBeAvailableAndSwitchToIt

public static ExpectedCondition<WebDriver> frameToBeAvailableAndSwitchToIt(WebElement frameLocator)
An expectation for checking whether the given frame is available to switch to.
If the frame is available it switches the given driver to the specified webelement.

Parameters:
frameLocator – used to find the frame (webelement)
Returns:
WebDriver instance after frame has been switched

invisibilityOfElementLocated

public static ExpectedCondition<java.lang.Boolean> invisibilityOfElementLocated(By locator)
An expectation for checking that an element is either invisible or not present on the DOM.
Parameters:
locator – used to find the element
Returns:
true if the element is not displayed or the element doesn’t exist or stale element

invisibilityOfElementWithText

public static ExpectedCondition<java.lang.Boolean> invisibilityOfElementWithText(By locator,
java.lang.String text)
An expectation for checking that an element with text is either invisible or not present on the DOM.
Parameters:
locator – used to find the element
text – of the element
Returns:
true if no such element, stale element or displayed text not equal that provided

elementToBeClickable

public static ExpectedCondition<WebElement> elementToBeClickable(By locator)
An expectation for checking an element is visible and enabled such that you can click it.
Parameters:
locator – used to find the element
Returns:
the WebElement once it is located and clickable (visible and enabled)

elementToBeClickable

public static ExpectedCondition<WebElement> elementToBeClickable(WebElement element)
An expectation for checking an element is visible and enabled such that you can click it.
Parameters:
element – the WebElement
Returns:
the (same) WebElement once it is clickable (visible and enabled)

stalenessOf

public static ExpectedCondition<java.lang.Boolean> stalenessOf(WebElement element)
Wait until an element is no longer attached to the DOM.
Parameters:
element – The element to wait for.
Returns:
false if the element is still attached to the DOM, true otherwise.

refreshed

public static <T> ExpectedCondition<T> refreshed(ExpectedCondition<T> condition)
Wrapper for a condition, which allows for elements to update by redrawing. This works around the problem of conditions which have two parts: find an element and then check for some condition on it. For these conditions it is possible that an element is located and then subsequently it is redrawn on the client. When this happens a StaleElementReferenceException is thrown when the second part of the condition is checked.
Type Parameters:
T – return type of the condition provided
Parameters:
condition – ExpectedCondition to wrap
Returns:
the result of the provided condition

elementToBeSelected

public static ExpectedCondition<java.lang.Boolean> elementToBeSelected(WebElement element)
An expectation for checking if the given element is selected.
Parameters:
element – WebElement to be selected
Returns:
true once the element is selected

elementSelectionStateToBe

public static ExpectedCondition<java.lang.Boolean> elementSelectionStateToBe(WebElement element,
boolean selected)
An expectation for checking if the given element is selected.
Parameters:
element – WebElement to be selected
selected – boolean state of the selection state of the element
Returns:
true once the element’s selection stated is that of selected

elementToBeSelected

public static ExpectedCondition<java.lang.Boolean> elementToBeSelected(By locator)

elementSelectionStateToBe

public static ExpectedCondition<java.lang.Boolean> elementSelectionStateToBe(By locator,
boolean selected)

alertIsPresent

public static ExpectedCondition<Alert> alertIsPresent()

numberOfwindowsToBe

@Deprecated
public static ExpectedCondition<java.lang.Boolean> numberOfwindowsToBe(int expectedNumberOfWindows)
Deprecated. please use numberOfWindowsToBe(int) instead

numberOfWindowsToBe

public static ExpectedCondition<java.lang.Boolean> numberOfWindowsToBe(int expectedNumberOfWindows)

not

public static ExpectedCondition<java.lang.Boolean> not(ExpectedCondition<?> condition)
An expectation with the logical opposite condition of the given condition. Note that if the Condition you are inverting throws an exception that is caught by the Ignored Exceptions, the inversion will not take place and lead to confusing results.
Parameters:
condition – ExpectedCondition to be inverted
Returns:
true once the condition is satisfied

attributeToBe

public static ExpectedCondition<java.lang.Boolean> attributeToBe(By locator,
java.lang.String attribute,
java.lang.String value)
An expectation for checking WebElement with given locator has attribute with a specific value
Parameters:
locator – used to find the element
attribute – used to define css or html attribute
value – used as expected attribute value
Returns:
Boolean true when element has css or html attribute with the value

textToBe

public static ExpectedCondition<java.lang.Boolean> textToBe(By locator,
java.lang.String value)
An expectation for checking WebElement with given locator has specific text
Parameters:
locator – used to find the element
value – used as expected text
Returns:
Boolean true when element has text value equal to @value

textMatches

public static ExpectedCondition<java.lang.Boolean> textMatches(By locator,
java.util.regex.Pattern pattern)
An expectation for checking WebElement with given locator has text with a value as a part of it
Parameters:
locator – used to find the element
pattern – used as expected text matcher pattern
Returns:
Boolean true when element has text value containing @value

numberOfElementsToBeMoreThan

public static ExpectedCondition<java.util.List<WebElement>> numberOfElementsToBeMoreThan(By locator,
java.lang.Integer number)
An expectation for checking number of WebElements with given locator
Parameters:
locator – used to find the element
number – used to define exact number of elements
Returns:
Boolean true when size of elements list is equal to defined

numberOfElementsToBeLessThan

public static ExpectedCondition<java.util.List<WebElement>> numberOfElementsToBeLessThan(By locator,
java.lang.Integer number)
An expectation for checking number of WebElements with given locator being less than defined number
Parameters:
locator – used to find the element
number – used to define maximum number of elements
Returns:
Boolean true when size of elements list is less than defined

numberOfElementsToBe

public static ExpectedCondition<java.util.List<WebElement>> numberOfElementsToBe(By locator,
java.lang.Integer number)
An expectation for checking number of WebElements with given locator
Parameters:
locator – used to find the element
number – used to define number of elements
Returns:
Boolean true when size of elements list is equal to defined

attributeToBe

public static ExpectedCondition<java.lang.Boolean> attributeToBe(WebElement element,
java.lang.String attribute,
java.lang.String value)
An expectation for checking given WebElement has attribute with a specific value
Parameters:
element – used to check its parameters
attribute – used to define css or html attribute
value – used as expected attribute value
Returns:
Boolean true when element has css or html attribute with the value

attributeContains

public static ExpectedCondition<java.lang.Boolean> attributeContains(WebElement element,
java.lang.String attribute,
java.lang.String value)
An expectation for checking WebElement with given locator has attribute which contains specific value
Parameters:
element – used to check its parameters
attribute – used to define css or html attribute
value – used as expected attribute value
Returns:
Boolean true when element has css or html attribute which contains the value

attributeContains

public static ExpectedCondition<java.lang.Boolean> attributeContains(By locator,
java.lang.String attribute,
java.lang.String value)
An expectation for checking WebElement with given locator has attribute which contains specific value
Parameters:
locator – used to define WebElement to check its parameters
attribute – used to define css or html attribute
value – used as expected attribute value
Returns:
Boolean true when element has css or html attribute which contains the value

attributeToBeNotEmpty

public static ExpectedCondition<java.lang.Boolean> attributeToBeNotEmpty(WebElement element,
java.lang.String attribute)
An expectation for checking WebElement any non empty value for given attribute
Parameters:
element – used to check its parameters
attribute – used to define css or html attribute
Returns:
Boolean true when element has css or html attribute with non empty value

visibilityOfNestedElementsLocatedBy

public static ExpectedCondition<java.util.List<WebElement>> visibilityOfNestedElementsLocatedBy(By parent,
By childLocator)
An expectation for checking child WebElement as a part of parent element to be visible
Parameters:
parent – used to check parent element. For example table with locator By.id(“fish”)
childLocator – used to find the ultimate child element.
Returns:
visible nested element

visibilityOfNestedElementsLocatedBy

public static ExpectedCondition<java.util.List<WebElement>> visibilityOfNestedElementsLocatedBy(WebElement element,
By childLocator)
An expectation for checking child WebElement as a part of parent element to be visible
Parameters:
element – used as parent element. For example table with locator By.xpath(“//table”)
childLocator – used to find child element. For example td By.xpath(“./tr/td”)
Returns:
visible subelement

presenceOfNestedElementLocatedBy

public static ExpectedCondition<WebElement> presenceOfNestedElementLocatedBy(By locator,
By childLocator)
An expectation for checking child WebElement as a part of parent element to present
Parameters:
locator – used to check parent element. For example table with locator By.xpath(“//table”)
childLocator – used to find child element. For example td By.xpath(“./tr/td”)
Returns:
subelement

presenceOfNestedElementLocatedBy

public static ExpectedCondition<WebElement> presenceOfNestedElementLocatedBy(WebElement element,
By childLocator)
An expectation for checking child WebElement as a part of parent element to be present
Parameters:
element – used as parent element
childLocator – used to find child element. For example td By.xpath(“./tr/td”)
Returns:
subelement

presenceOfNestedElementsLocatedBy

public static ExpectedCondition<java.util.List<WebElement>> presenceOfNestedElementsLocatedBy(By parent,
By childLocator)
An expectation for checking child WebElement as a part of parent element to present
Parameters:
parent – used to check parent element. For example table with locator By.xpath(“//table”)
childLocator – used to find child element. For example td By.xpath(“./tr/td”)
Returns:
subelement

invisibilityOfAllElements

public static ExpectedCondition<java.lang.Boolean> invisibilityOfAllElements(WebElement… elements)
An expectation for checking all elements from given list to be invisible
Parameters:
elements – used to check their invisibility
Returns:
Boolean true when all elements are not visible anymore

invisibilityOfAllElements

public static ExpectedCondition<java.lang.Boolean> invisibilityOfAllElements(java.util.List<WebElement> elements)
An expectation for checking all elements from given list to be invisible
Parameters:
elements – used to check their invisibility
Returns:
Boolean true when all elements are not visible anymore

invisibilityOf

public static ExpectedCondition<java.lang.Boolean> invisibilityOf(WebElement element)
An expectation for checking the element to be invisible
Parameters:
element – used to check its invisibility
Returns:
Boolean true when elements is not visible anymore

or

public static ExpectedCondition<java.lang.Boolean> or(ExpectedCondition<?>… conditions)
An expectation with the logical or condition of the given list of conditions. Each condition is checked until at least one of them returns true or not null.
Parameters:
conditions – ExpectedCondition is a list of alternative conditions
Returns:
true once one of conditions is satisfied

and

public static ExpectedCondition<java.lang.Boolean> and(ExpectedCondition<?>… conditions)
An expectation with the logical and condition of the given list of conditions. Each condition is checked until all of them return true or not null
Parameters:
conditions – ExpectedCondition is a list of alternative conditions
Returns:
true once all conditions are satisfied

javaScriptThrowsNoExceptions

public static ExpectedCondition<java.lang.Boolean> javaScriptThrowsNoExceptions(java.lang.String javaScript)
An expectation to check if js executable. Useful whenyou know that there should be a Javascript value or something at the stage.
Parameters:
javaScript – used as executable script
Returns:
true once javaScript executed without errors

jsReturnsValue

public static ExpectedCondition<java.lang.Object> jsReturnsValue(java.lang.String javaScript)
An expectation for String value from javascript
Parameters:
javaScript – as executable js line
Returns:
true once js return string

  • presence_of_element_located
  • visibility_of_element_located
  • visibility_of
  • invisibility_of_element_located
  • presence_of_all_elements_located
  • text_to_be_present_in_element
  • text_to_be_present_in_element_value
  • element_to_be_clickable
  • staleness_of
  • element_to_be_selected
  • element_located_to_be_selected
  • element_selection_state_to_be
  • element_located_selection_state_to_be
  • title_is
  • title_contains
  • alert_is_present
  • frame_to_be_available_and_switch_to_it

Hmm, that looks impressive. It means we can specify more special conditions like wait until the element is clickable or wait until a particular text is displayed?

Absolutely. Here is one more example:

wait.until(ExpectedConditions.alertIsPresent());
wait.until(EC.alert_is_present())

How would I get to know where to use Implicit Wait and where Explicit Wait?

Well, this is really a tough question. You can get the answer only by practising more and more. The more you play with the code, the more you would get comfortable with Selenium, and the more you’ll understand where to use what. It totally depends on the situation.

WARNING: Do not mix implicit and explicit waits. Doing so can cause unpredictable wait times. For example setting an implicit wait of 10 seconds and an explicit wait of 15 seconds, could cause a timeout to occur after 20 seconds.

This was the end of the series on Waits. In the Next Tutorial, we’ll learn to handle Popup windows and Alert dialog.

6 thoughts on “Waits | Explicit wait”

  1. I'm a bit lazy, but tried following 🙂

    public static void main(String[] args) {
    WebDriver driver = new FirefoxDriver();

    driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
    driver.manage().window().maximize();
    driver.get("http://www.cosmotechies.com/teachmeselenium/p/automation-practice.html&quot;);

    WebDriverWait wait = new WebDriverWait(driver,5);

    if(driver.findElements(By.id("firstname")).size() > 0)
    driver.findElement(By.id("firstname")).sendKeys("TestFirstName");

    driver.findElement(By.className("lastname")).sendKeys("TestLastName");

    driver.findElement(By.xpath("//input[@value='Male']")).click();

    driver.findElement(By.cssSelector("input[value=java]")).click();

    WebElement lstAge = driver.findElement(By.name("age"));
    Select selectAge = new Select(lstAge);
    selectAge.selectByVisibleText("30 to 39");

    driver.findElement(By.name("submit")).click();

    driver.findElement(By.partialLinkText("GoToHomepage")).click();
    wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("search")));

    driver.quit();

    Reply
  2. It is great to see another lazy man like me 🙂 …. Good work… It is preferred to use presenseOfElementLocated beforev / over visibilityOfElementLocated .. Because visibility just says elemnet is visible in page or not. it will wait until the element becomes visible. Sometimes an element is present in page source code but takes time to be visible (or on some end user action it becomes visible). Here is a catch. If element is not at all present in page then visibility will throw exception because it cannot check visibility of something which is not at all present in page.

    Reply
  3. "Wherever really needed, before performing any action on any element use Implicit Waits to wait for specific conditions."

    i think the above line has a typo , it should be "Explicit waits" , as
    there are 3 points
    1) implicit waits
    2) findelements
    so 3) should be about "explicit wait" and not implicit

    Reply

Leave a Reply