Skip to main content
Version: 10.2.9

Use WebDriver waits

How to handle Ajax call using WebDriver

The biggest challenge in handling an Ajax call is determining how long the webpage takes to load.

Since Ajax-based content loads within fractions of a second, it can be difficult to test such applications using automation tools. To handle this, WebDriver must apply a wait method to the Ajax call.

When executing a wait command, WebDriver pauses the execution of the current test case until the expected condition or new value appears. Once a new value or field is detected, WebDriver resumes executing the suspended test case.

You can use the following wait methods in WebDriver:

  • ImplicitWait() instructs WebDriver to wait if an element is not immediately available. This wait applies globally for the entire browser session, so any element search will wait up to the specified time before throwing an exception.

  • ExplicitWait() freezes the test execution until a specific condition is met or the maximum timeout is reached.

  • WebDriverWait is used with ExpectedConditions. The method checks for a specified condition every second and proceeds as soon as the condition is met. It is the most effective way to dynamically wait for elements.

note

You must specify a timeout unit for all waits. If the element does not appear within that time, you can use a fluent wait, which provides more control.

  • FluentWait defines the maximum wait time for a condition and how frequently to check it. Each FluentWait instance specifies both a timeout and a polling interval.

  • Thread.Sleep() is not recommended as it suspends the current thread for a specified time, regardless of whether the element is available or not. Because Ajax responses are unpredictable, using Thread.Sleep() can cause unnecessary delays or failed tests. It also increases system overhead by blocking the current thread.

The challenges in handling Ajax calls in WebDriver are as follows:

  • Using a pause command to handle Ajax calls is not unreliable. Long pauses slow down the test unnecessarily. Instead, use conditional waits such as waitForCondition.
  • It is difficult to assess the risks associated with certain Ajax applications.
  • Frequent changes to an Ajax application by developers make automated testing more complex.

Thus, the summary is as follows:

  • Ajax allows a webpage to retrieve small amounts of data from the server without reloading it entirely.
  • To test an Ajax application, use one of the following wait methods:
    • ThreadSleep
    • ImplicitWait
    • ExplicitWait
    • WebdriverWait
    • FluentWait
  • Automated testing of Ajax applications can be challenging because they often use different encoding or serialization techniques when sending POST data.

Why do you need waits in web automation?

Most modern web applications use Ajax and JavaScript. When a webpage loads, elements you want to interact with can appear at different times. This makes it difficult for automation scripts to locate elements. If an element is not found, an ElementNotVisibleException exception is thrown. Waits help prevent this issue.

Let's consider a scenario where you use both implicit and explicit waits. Assume that an implicit wait is set to 20 seconds and an explicit wait is set to 10 seconds. An element defined by ExpectedConditions is not found within 10 seconds, and the implicit wait still applies (20 seconds total) before throwing ElementNotVisibleException.

Implicit waits versus explicit waits

ParameterExplicit waitImplicit wait
SideClient sideDriver side
Timing500 ms (lower)1000 ms (higher)
AutomaticNo, applies only to elements specified by the user.Yes, applies to all elements in the script.
Need to specify ExpectedConditions in the element to be located.YesNo
Use CaseRecommended when elements take time to load or when verifying element properties such as visibilityOfElementLocated, elementToBeClickable, or elementToBeSelected.Recommended when elements generally load within the timeframe set by the implicit wait.
Wait for what?
  • Do not use to check if an element is present.
  • Can wait for any condition.
Used with methods:
  • driver.findElement()
  • driver.findelements()
Waits until the elements appear in the DOM.
Exception typeTimeoutExceptionNoSuchElementException
Network calls countMultipleSingle
info
  • Implicit, explicit, and fluent waits are all supported in WebDriver.
  • Avoid using Thread.Sleep().
  • Choose the appropriate wait based on element load times.
  • Set Default polling interval to 100 ms.

Implicit waits

An implicit wait tells WebDriver to wait a specified amount of time before throwing "No Such Element Exception". The default is 0. Once set, the same wait time applies throughout the session.

In the below example, an implicit 10-second wait is declared. If an element is not located on a webpage within 10 seconds, it throws an exception.

To declare an implicit wait, do as follows:

timeouts().implicitlyWait(TimeOut, TimeUnit.SECONDS);

In the above example, line 19 defines an implicit wait with two parameters:

  • The first parameter accepts the time as an integer value.
  • The second parameter accepts the time measurement in terms of minutes, seconds, milliseconds, and so on.

Explicit waits

An explicit wait tells WebDriver to wait for certain ExpectedConditions or until the timeout is exceeded before throwing ElementNotVisibleException.

Explicit waits are more flexible than implicit waits, as they apply to specific elements and are ideal for handling dynamically loaded Ajax content.

Once you declare an explicit wait, use the ExpectedConditions class or configure how frequently you want to check a condition using a fluent wait.

In the example below, a reference wait for the WebDriverWait class and instantiating using the WebDriver reference are created, with the maximum timeframe of 20 seconds:

WebDriverWait wait = new WebDriverWait(WebDriverRefrence,TimeOut);

  • Line 22 defines a 20-second explicit wait using the WebDriverWait class (1).

  • Line 39 applies the wait to an element as defined in the WebDriverWait class on the webpage until ExpectedConditions are met, and the condition is visibilityofElementLocated (2).

The common ExpectedConditions methods in the explicit wait are as follows:

  • alertIsPresent()
  • elementSelectionStateToBe()
  • elementToBeClickable()
  • elementToBeSelected()
  • frameToBeAvaliableAndSwitchToIt()
  • invisibilityOfTheElementLocated()
  • invisibilityOfElementWithText()
  • presenceOfAllElementsLocatedBy()
  • presenceOfElementLocated()
  • textToBePresentInElement()
  • textToBePresentInElementLocated()
  • textToBePresentInElementValue()
  • titleIs()
  • titleContains()
  • visibilityOf()
  • visibilityOfAllElements()
  • visibilityOfAllElementsLocatedBy()
  • visibilityOfElementLocated()

Test automation scripts should synchronize with the website every time they interact with website elements. The synchronization is done using explicit waits and expected conditions.

Why do you need explicit waits?

Let's take the simplest driver.findElement(locator) method in WebDriver. findElement() searches for an element that matches the specified locator in the browser's DOM.

  • If the element is found, findElement() returns it.
  • If the element is not found, findElement() throws an exception and the test fails. However, if the website is slow and the elements are not yet present in the DOM when findElement() executes, it fails. To prevent this, you should wait until the elements are available in the DOM before interacting with them.

What are explicit waits?

An explicit wait uses the WebDriverWait class. It takes the instance and a timeout value as parameters:

WebDriverWait wait = new WebDriverWait(driver, timeout);

The explicit wait works by pausing execution until a specific condition is met. This condition is defined using the ExpectedConditions class:

wait.until(ExpectedConditions.condition(parameters));

Here's an example of how an explicit wait works:

WebDriverWait wait; wait = new WebDriverWait(driver, 10); WebElement element; element=wait.until(ExpectedConditions. elementToBeClickable(locator));
  1. The wait object is created using the driver instance and a 10-second timeout.

  2. The until() method starts a timer.

  3. The until() method repeatedly checks whether the expected condition is met—in this case, whether the element is present in the DOM and clickable.

  4. If the condition is satisfied, the until() method returns the element, and the wait ends successfully.

  5. If the condition is not met but the timeout has not yet expired, the process continues from step 3.

  6. If the timeout is reached and the condition is still not met, the explicit wait throws an error.

When can you use explicit waits?

You can use explicit waits in the following scenarios:

  • To find a single web element.
  • To find multiple web elements.
  • To verify the webpage title and URL.
  • To the state or visibility of an element.
  • To interact with frames.
tip

Use these expected conditions to locate elements instead of directly calling driver.findElement().

Code samples

elementToBeClickable
ExpectedCondition<WebElement> elementToBeClickable(By locator) ExpectedCondition<WebElement> elementToBeClickable(WebElement element)

Defines an expectation for checking that an element is visible and enabled so that you can click it.

Example: The following two lines of code search for the element that matches the locator.

If the element can be found in the browser's DOM and is clickable within 10 seconds, it is returned and stored in a WebElement variable.

The locator can be XPath, CSS, ID, or name locator.

WebDriverWait wait = new WebDriverWait(driver, 10); WebElement element; element = wait.until(ExpectedConditions. elementToBeClickable(locator));
presenceOfElementLocated
ExpectedCondition<WebElement> presenceOfElementLocated(By locator)

Defines an expectation for checking that an element is present in the page DOM.

Example: The following two lines of code search for the element that matches the locator.

If the element can be found in the browser's DOM within 10 seconds, it is returned and stored in a WebElement variable.

The locator can be XPath, CSS, ID, or name locator.

WebDriverWait wait = new WebDriverWait(driver, 10); WebElement element; element = wait.until(ExpectedConditions. presenceOfElementLocated(locator));
visibilityOfElementLocated
ExpectedCondition<WebElement> visibilityOfElementLocated(By locator) ExpectedCondition<WebElement> visibilityOf(WebElement element)

Defines an expectation for checking that an element is present in the page DOM and is visible.

Example: The following two lines of code search for the element that matches the locator.

If the element can be found in the browser's DOM and is visible within 10 seconds, it is returned and stored in a WebElement variable.

The locator can be XPath, CSS, ID, or name locator.

WebDriverWait wait = new WebDriverWait(driver, 10); WebElement element; element = wait.until(ExpectedConditions. visibilityOfElementLocated(locator));

The following expected conditions can be used to find multiple web elements. It is recommended to use them instead of driver.findElements().

visibilityOfAllElementsLocatedBy
ExpectedCondition<List<WebElement>> visibilityOfAllElementsLocatedBy(By locator) ExpectedCondition<List<WebElement>> visibilityOfAllElements(List<WebElement> elements)

Defines an expectation for checking that all elements present on the webpage that match the locator are visible.

Example: The following two lines of code search for all elements that match the locator.

If the elements can be found in the browser's DOM and are visible within 10 seconds, they are returned and stored in a list of WebElement variables.

The locator can be XPath, CSS, ID, or name locator.

WebDriverWait wait = new WebDriverWait(driver, 10); List<WebElement> elements; elements =wait.until(ExpectedConditions. visibilityOfAllElementsLocatedBy(locator));
presenceOfAllElementsLocatedBy
ExpectedCondition<List<WebElement>> presenceOfAllElementsLocatedBy(By locator)

Defines an expectation for checking whether there is at least one element present on the webpage.

Example: The following two lines of code search for all elements that match the locator.

If elements can be found in the browser's DOM within 10 seconds, they are returned and stored in a list of WebElement variables.

The locator can be XPath, CSS, ID, or name locator.

WebDriverWait wait = new WebDriverWait(driver, 10); List<WebElement> elements; elements = wait.until(ExpectedConditions. presenceOfAllElementsLocatedBy(locator));

The following expected conditions can be used to check the webpage title and URL. It is recommended to use them instead of driver.getTitle() and driver.getCurrentUrl().

titleContains
ExpectedCondition<java.lang.Boolean> titleContains(java.lang.String title)

Defines an expectation for checking whether the title contains a case-sensitive substring.

Example: The following two lines of code verify if the page title contains a keyword.

If the keyword is found in the page title within 10 seconds, the explicit wait returns true. Otherwise, it returns false.

WebDriverWait wait = new WebDriverWait(driver, 10); assertTrue(wait.until(ExpectedConditions. titleContains(keyword)));
titleIs
ExpectedCondition<java.lang.Boolean>
titleIs(java.lang.String title)

Defines an expectation for checking the title of a page.

Example: The following two lines of code verify whether the page title is equal to a specific value.

If the page title matches the expected value within 10 seconds, the explicit wait returns true. Otherwise, it returns false.

WebDriverWait wait = new WebDriverWait(driver, 10);
assertTrue(wait.until(ExpectedConditions.
titleIs(titleValue)));
urlContains
ExpectedCondition<java.lang.Boolean>
urlContains(java.lang.String fraction)

Defines an expectation for checking whether the URL of the current page contains specific text.

Example: The following two lines of code verify whether the page URL contains a keyword.

If the keyword is found in the page URL within 10 seconds, the explicit wait returns true. Otherwise, it returns false.

WebDriverWait wait = new WebDriverWait(driver, 10);
assertTrue(wait.until(ExpectedConditions.
urlContains(keyword)));
urlToBe
ExpectedCondition<java.lang.Boolean>
urlToBe(java.lang.String url)

Defines an expectation for checking whether the URL of the current page matches a specific URL.

Example: The following two lines of code verify whether the page URL equals a specific value.

If the page URL matches the expected value within 10 seconds, the explicit wait returns true. Otherwise, it returns false.

WebDriverWait wait = new WebDriverWait(driver, 10);
assertTrue(wait.until(ExpectedConditions.
urlToBe(urlValue)));
urlMatches
ExpectedCondition<java.lang.Boolean>
urlMatches(java.lang.String regex)

Defines an expectation for checking whether the URL matches a specific regular expression.

Example: The following two lines of code verify whether the page URL matches a regular expression.

If the page URL matches the regular expression within 10 seconds, explicit wait returns true. Otherwise, it returns false.

WebDriverWait wait = new WebDriverWait(driver, 10);
assertTrue(wait.until(ExpectedConditions.
urlMatches(regularExpression)));

You can use these expected conditions to verify an element’s status. They are ideal for assertions.

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

ExpectedCondition<java.lang.Boolean>
elementSelectionStateToBe(WebElement element, boolean selected)

Defines an expectation for checking whether a given element is selected.

Example: The following two lines of code verify whether the element is selected.

If the element is selected within 10 seconds, the explicit wait returns true. Otherwise, it returns false.

WebDriverWait wait = new WebDriverWait(driver, 10);
assertTrue(wait.until(ExpectedConditions.
elementSelectionStateToBe(locator, true)));
elementToBeSelected
ExpectedCondition<java.lang.Boolean>
elementToBeSelected(By locator)

ExpectedCondition<java.lang.Boolean>
elementToBeSelected(WebElement element)

Defines an expectation for checking whether a given element is selected.

Example: The following two lines of code verify whether the element is selected.

If the element is selected within 10 seconds, the explicit wait returns true. Otherwise, it returns false.

WebDriverWait wait = new WebDriverWait(driver, 10);
assertTrue(wait.until(ExpectedConditions.
elementToBeSelected(locator)));
invisibilityOfElementLocated
ExpectedCondition<java.lang.Boolean>
invisibilityOfElementLocated(By locator)

Defines an expectation for checking that an element is either invisible or not present in the DOM.

Example: The following two lines of code verify whether the element is invisible.

If the element becomes invisible within 10 seconds, the explicit wait returns true. Otherwise, it returns false.

WebDriverWait wait = new WebDriverWait(driver, 10);
assertTrue(wait.until(ExpectedConditions.
invisibilityOfElementLocated(locator)));
invisibilityOfElementWithText
ExpectedCondition<java.lang.Boolean>
invisibilityOfElementWithText(By locator, java.lang.String text)

Defines an expectation for checking that an element with text is either invisible or not present in the DOM.

Example: The following two lines of code verify whether the element is invisible.

If the element becomes invisible within 10 seconds, the explicit wait returns true. Otherwise, it returns false.

WebDriverWait wait = new WebDriverWait(driver, 10);
assertTrue(wait.until(ExpectedConditions.
invisibilityOfElementWithText(locator, text)));
stalenessOf
ExpectedCondition<java.lang.Boolean>
stalenessOf(WebElement element)

Wait until an element is no longer attached to the DOM.

Example: The following two lines of code verify whether the element is no longer part of the browser's DOM.

If the element is removed from the DOM within 10 seconds, the explicit wait returns true. Otherwise, it returns false.

WebDriverWait wait = new WebDriverWait(driver, 10);
assertTrue(wait.until(ExpectedConditions.
stalenessOf(element)));
textToBePresentInElement
ExpectedCondition<java.lang.Boolean>
textToBePresentInElement(WebElement element, java.lang.String text)

ExpectedCondition<java.lang.Boolean>
textToBePresentInElementLocated(By locator, java.lang.String text)

Defines an expectation for checking whether specific text is present in the element that matches the given locator.

Example: The following two lines of code verify whether a keyword is included in an element.

If the keyword is found in the element within 10 seconds, the explicit wait returns true. Otherwise, it returns false.

WebDriverWait wait = new WebDriverWait(driver, 10);
assertTrue(wait.until(ExpectedConditions.
textToBePresentInElementLocated(locator, keyword)));
textToBePresentInElementValue
ExpectedCondition<java.lang.Boolean>
textToBePresentInElementValue(By locator, java.lang.String text)

ExpectedCondition<java.lang.Boolean>
textToBePresentInElementValue(WebElement element, java.lang.String text)

Defines an expectation for checking whether specific text is present in the value attributes of an element.

Example: The following two lines of code verify whether a keyword is included in the value attribute of the element.

If the keyword is found in the element's value attribute within 10 seconds, the explicit wait returns true. Otherwise, it returns false.

WebDriverWait wait = new WebDriverWait(driver, 10);
assertTrue(wait.until(ExpectedConditions.
textToBePresentInElementValue(locator, keyword)));
isElementPresent

Below is the syntax for checking the presence of an element using WebDriverWait. The example shows how to pass the wait time and locator as parameters to the method. This check verifies whether an element is present in the page DOM. It does not necessarily mean the element is visible. ExpectedConditions returns true once the element is found in the DOM.

WebDriverWait wait = new WebDriverWait(driver, waitTime);
wait.until(ExpectedConditions.presenceOfElementLocated(locator));

Use presenceOfElementLocated when you do not care about the element's visibility and only need to confirm that it exists on the page.

You can also use the following syntax to check whether an element is present. Return true only when the element list size is greater than 0, meaning that at least one element exists.

WebElement element = driver.findElements(By.cssSelector(""));
element.size()>0;
isElementClickable

Below is the syntax for checking whether an element is visible and enabled so that you can click it. You must pass the wait time and locator as parameters.

WebDriverWait wait = new WebDriverWait(driver, waitTime);
wait.until(ExpectedConditions.elementToBeClickable(locator));
isElementVisible

Below is the syntax for checking whether an element is present in the page DOM and visible. Visibility means that the element is not only displayed but also has a height and width greater than 0.

WebDriverWait wait = new WebDriverWait(driver, waitTime);
wait.until(ExpectedConditions.visibilityOfElementLocated(locator));

You can also use the following code to check that a WebElement is visible:

WebDriverWait wait = new WebDriverWait(driver, waitTime);
wait..until(ExpectedConditions.visibilityOf(element));

You can also use the following code to check that all elements present on the webpage are visible. Pass a list of WebElements as a parameter:

List<WebElement> linkElements = driver.findelements(By.cssSelector('#linkhello'));
WebDriverWait wait = new WebDriverWait(driver, waitTime);
wait..until(ExpectedConditions.visibilityOfAllElements(linkElements));
isElementInVisible

Below is the syntax for checking whether an element is invisible or not present in the DOM.

WebDriverWait wait = new WebDriverWait(driver, waitTime);
wait.until(ExpectedConditions.invisibilityOfElementLocated(locator));
isElementEnabled

Below is the syntax for checking whether the element is enabled.

WebElement element = driver.findElement(By.id(""));
element.isEnabled();
isElementDisplayed

Below is the syntax for checking whether the element is displayed. It returns false when the element is not present in the DOM.

WebElement element = driver.findElement(By.id(""));
element.isDisplayed();
Wait for invisibility of element

Below is the syntax for checking whether an element with text is invisible:

WebDriverWait wait = new WebDriverWait(driver, waitTime);
wait.until(ExpectedConditions.invisibilityOfElementWithText(by));
Wait for invisibility of element with text

Below is the syntax for checking that an element with text is invisible or not present in the DOM.

WebDriverWait wait = new WebDriverWait(driver, waitTime);
wait.until(ExpectedConditions.invisibilityOfElementWithText(by, strText));

Fluent waits

A fluent wait instructs WebDriver to wait for a specific condition and defines how frequently the condition should be checked before throwing ElementNotVisibleException.

The polling frequency determines how often WebDriver checks whether the condition is met within the given timeout period.

Consider a scenario where an element is loaded at varying time intervals, for example, within 10 seconds, 20 seconds, or even longer. If you use an explicit wait with a 20-second timeout, WebDriver waits for the entire duration before throwing an exception.

In such cases, it is recommended to use a fluent wait, as it repeatedly checks for the element at a defined polling interval until the element is found or the timeout expires.

Wait wait = new FluentWait(WebDriver reference).withTimeout(timeout, SECONDS).pollingEvery(timeout, SECONDS).ignoring(Exception.class);

  • Line 39 declares a fluent wait with the timeout of 30 seconds and sets the frequency to 5 seconds by ignoring NoSuchElementException:

    Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)                           
    .withTimeout(30, TimeUnit.SECONDS)
    .pollingEvery(5, TimeUnit.SECONDS)
    .ignoring(NoSuchElementException.class);
  • Line 46 contains a new function created to identify the web element on the page. For example, here, the web element is nothing but the web link on the webpage.

    The frequency is set to 5 seconds, and the timeout is set to 30 seconds. If the element is located within this timeframe, it performs the operations. Otherwise, it throws ElementNotVisibleException.

    WebElement clickweblink = wait.until(new Function<WebDriver, WebElement>() {                         
    public WebElement apply(WebDriver driver) {
    return driver.findElement(By.xpath("//*[@id='java_technologies']/li[3]/a"));
    }
    });
    //click the guru99 web link
    clickweblink.click();

Sleep command

The Thread.Sleep command is rarely used as it forces the browser to pause for a fixed duration. It is rarely used in modern test automation because it blocks execution and makes tests slower and less reliable.

Instead, use WebDriver's built-in wait primitives (implicit, explicit, or fluent waits) that evaluate conditions dynamically.

Thread.sleep(3000);
troubleshooting

For troubleshooting tips, see the following support guides: