Selenium WebDriverWait: Implementing The Explicit Wait Command
Tags: selenium, seleniumwebdriver, softwaretesting, automationtesting
Published: 2023-08-21 09:31:11

In the dynamic realm of automation testing, achieving flawless execution and dependable results is of utmost importance. As web applications grow more intricate and user-centric, conventional test scripts may struggle to handle asynchronous behavior and varying loading times. This is where ***Selenium WebDriverWait*** emerges as a game-changer.

*WebDriverWait*, a potent feature of Selenium, the industry-standard web application testing tool, empowers testers to apply intelligent delays or “waits” in their scripts. These waits ensure that interactions with web elements occur precisely when they are ready, rather than being forced prematurely. In this blog, we will delve into the significance of Wait commands in automation testing and explore how Selenium’s WebDriverWait elevates the efficiency and accuracy of test suites. By addressing the challenges posed by asynchronous web applications, network latencies, cross-browser inconsistencies, and UI rendering, WebDriverWait not only enhances test stability and reliability but also improves overall test performance.

In this blog, we will briefly look at the concept of the *Explicit Wait* command in Selenium. Subsequently, we will look at Selenium ***WebDriverWait***, a Java class that implements the Explicit Wait command.

We will discuss the benefits of Selenium *WebDriverWait* in [automation testing](https://www.lambdatest.com/automation-testing?utm_source=devto&utm_medium=organic&utm_campaign=aug_21&utm_term=ap&utm_content=webpage). We’ll also explore ***ExpectedConditions*** in *Selenium*, covering its types and commonly used *expected conditions*. We’ll provide an illustrative example to demonstrate the implementation of Selenium WebDriverWait. This comprehensive approach will equip you with a strong foundation in working with one of the Wait Commands in Selenium.

***Need a great solution for cross browser testing on Safari? Forget about emulators or simulators — use real online browsers. Try LambdaTest to test on*** [***safari browser online***](https://www.lambdatest.com/test-on-safari-browsers?utm_source=devto&utm_medium=organic&utm_campaign=aug_21&utm_term=ap&utm_content=webpage)***.***

### What is Selenim WebDriverWait?

Selenium WebDriver offers different types of ***Wait Commands*** to handle synchronization in test automation. The concept of Selenium Wait revolves around pausing the execution of the script until certain conditions are met, ensuring that the test proceeds only when the desired state or element is available.

There are three types of Wait Commands:

1. Implicit Wait Command
    
2. Explicit Wait Command
    
3. Fluent Wait Command
    

![image](https://cdn-images-1.medium.com/max/800/0*Q0wZ-AMVqj28CAWf.png align="left")

**“WebDriverWait”** is a class in Java provided by the [Selenium framework](https://www.lambdatest.com/blog/selenium-framework/?utm_source=devto&utm_medium=organic&utm_campaign=aug_21&utm_term=ap&utm_content=blog) that allows you to implement the concept of Explicit Waits in your test automation scripts. It allows you to define custom wait conditions and specify the maximum duration for the WebDriver to wait until the condition is satisfied. It provides control and flexibility compared to Implicit Waits, which are based on a fixed waiting time.

Selenium *WebDriverWait* class allows defining expected conditions using built-in methods provided by the ***ExpectedConditions*** class, such as element visibility, element clickability, text presence, and many more.

You may check out our blog on [Selenium Wait](https://www.lambdatest.com/blog/types-of-waits-in-selenium/?utm_source=devto&utm_medium=organic&utm_campaign=aug_21&utm_term=ap&utm_content=blog) to learn in-depth about the Selenium Wait commands.

***Test your native, hybrid, and web apps across all legacy and latest mobile operating systems on the most powerful*** [***online Android emulator***](https://www.lambdatest.com/android-emulator-online?utm_source=devto&utm_medium=organic&utm_campaign=aug_21&utm_term=ap&utm_content=webpage)***.***

### Benefits of Using WebDriverWait

The implementation of the Explicit Wait command using the Selenium *WebDriverWait* class offers various benefits as listed below:

* [Selenium WebDriverWait](https://www.lambdatest.com/blog/webdriverwait-in-selenium-c-sharp/?utm_source=devto&utm_medium=organic&utm_campaign=aug_21&utm_term=ap&utm_content=blog) allows your test scripts to wait for specific conditions to be met before proceeding, ensuring that the elements are ready for interaction. This reduces the chances of encountering errors or failures due to time-related issues.
    
* Selenium WebDriverWait is particularly useful for handling dynamic web pages where elements may appear or change asynchronously. It enables you to wait for elements to be visible, clickable, or present before interacting with them, accommodating the dynamic nature of web applications.
    
* Selenium WebDriverWait offers the flexibility to define custom wait conditions tailored to your specific testing requirements. You can create conditions based on JavaScript, CSS, or other relevant techniques, allowing you to handle unique scenarios not covered by built-in expected conditions.
    

### Getting Started with Explicit Wait using Selenium WebDriverWait Class in Java

The Explicit Wait is a more intelligent approach than the Implicit Wait to handle synchronization in automation testing. Unlike Implicit, Explicit Wait allows you to pause the program execution for specific elements until they meet the desired conditions. It also provides more control and flexibility and is especially useful for waiting on dynamically loaded Ajax elements.

To use Explicit Wait, you must utilize the *ExpectedConditions* provided by Selenium.

Let’s discuss the *ExpectedConditions* in Selenium Webdriver.

### ExpectedCondition in Selenium Webdriver

In automation testing, ensuring that the rendering of the web page and your instructions are in sync before proceeding is essential. Therefore, *Selenium WebDriver* provided [ExpectedConditions](https://www.lambdatest.com/learning-hub/webdriver?utm_source=devto&utm_medium=organic&utm_campaign=aug_21&utm_term=ap&utm_content=learning_hub) that are used for performing Explicit Waits on a certain condition. These conditions are accessible in various programming languages and provide a user-friendly approach to waiting for specific conditions to be fulfilled. The availability of these conditions may differ based on the Selenium language bindings used.

### Types of ExpectedConditions in Selenium Java

There are generally four categories of Expected Conditions in Selenium Java,

1. ExpectedCondition&lt; WebElement &gt;
    
2. ExpectedCondition&lt; WebDriver &gt;
    
3. ExpectedCondition&lt; Boolean &gt;
    
4. ExpectedCondition&lt; Alert &gt;
    

We will not look at each of these Expected Conditions one by one in detail.

#### ExpectedCondition &lt; WebElement &gt;

This ExpectedCondtions uses the WebElement as a parameter. Then the Explicit Wait is performed until the specified expected condition is fulfilled or the specified wait duration is reached. When the expected condition is fulfilled, it returns the corresponding WebElement, a list of WebElements, or other relevant information based on the core implementation of the ExpectedCondition.

#### ExpectedCondition &lt; WebDriver &gt;

This allows you to wait for WebDriver-related conditions to be satisfied before moving forward with your test execution. Once the specified operations are successfully performed, the method returns the WebDriver instance, indicating that the desired conditions have been met.

#### ExpectedCondition &lt; Boolean &gt;

This represents a condition that returns a Boolean value. It is used in Explicit Waits to wait for specific conditions to be satisfied and to return a Boolean value as a result indicating whether the condition has been met or not.

#### ExpectedCondition &lt; Alert &gt;

This represents a condition to wait for the presence of an alert on a web page. This type of condition is used in Explicit Waits to wait for an alert to be present. Once the alert is present, you can interact with it using methods like accept() to accept the alert or dismiss() to dismiss it.

We have discussed the different categories of *ExpectedConditions* in Selenium Java. Now, Let’s explore some of the commonly used *ExpectedConditions* in Selenium Java to implement Explicit Waits.

### Commonly used ExpectedConditions in Selenium Java

In this section, we are going to look at the static methods provided in the *ExpectedConditions* class in Java. We will see how to use them in a practical way by writing Selenium Test Scripts.

### elementToBeClickable Method

It is a method of ExpectedCondition that waits for an element to be clickable. This is especially useful in scenarios where elements may take some time to load, become enabled, or change state based on certain conditions.

**Method Category** — ExpectedCondition&lt; WebElement &gt;

Syntax –

```plaintext
ExpectedCondition<WebElement> elementToBeClickable​(By locator)
```

### presenceOfElementLocated​ Method

This method is used to wait for the presence of a specific element on a web page. It checks whether the element is available in the [DOM (Document Object Model)](https://www.lambdatest.com/blog/document-object-model/?utm_source=devto&utm_medium=organic&utm_campaign=aug_21&utm_term=ap&utm_content=blog) of the page or not. If the element is found, the method returns the WebElement, indicating that the element is now ready for further interactions in your automation testing. In other words, it ensures that the element is loaded and can be accessed before proceeding with any actions on it.

**Method Category** — ExpectedCondition&lt; WebElement &gt;

Syntax-

```plaintext
ExpectedCondition<WebElement> presenceOfElementLocated​(By locator)
```

### visibilityOfElementLocated​ Method

This method waits for an element to be both present in the DOM and visible on the web page before proceeding with the [test execution](https://www.lambdatest.com/learning-hub/test-execution?utm_source=devto&utm_medium=organic&utm_campaign=aug_21&utm_term=ap&utm_content=learning_hub). Similar to the **presenceOfElementLocated​** Method, this also checks if the element is present in the DOM of the page. But this method does one thing extra as this checks if the element also has a non-zero size, meaning it is visible to the user on the web page or not. If the element meets both conditions, the method returns the WebElement, indicating that the element is now visible and is available for further interactions.

**Method Category** — ExpectedCondition&lt; WebElement &gt;

Syntax-

```plaintext
ExpectedCondition<WebElement> visibilityOfElementLocated​(By locator)
```

### visibilityOfAllElementsLocatedBy​ Method

This method is similar to the visibilityOfElementLocated​ Method. The only difference is that it waits for all elements matching a specific locator to be both present in the DOM and visible on the web page before proceeding with the test execution.

**Method Category** — ExpectedCondition&lt; WebElement &gt;

Syntax-

```plaintext
ExpectedCondition<WebElement> visibilityOfAllElementsLocatedBy​(By locator)
```

Let’s take an example to understand the above method.  
(We will implement various tests using the [LambdaTest’s Demo Website](https://www.lambdatest.com/automation-demos?utm_source=devto&utm_medium=organic&utm_campaign=aug_21&utm_term=ap&utm_content=webpage))

```plaintext
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.time.Duration;
import java.util.List;

public class SeleniumWebDriverWaitExample {

  public static void main(String[] args) {
  WebDriver driver = new ChromeDriver();
  // Navigate to the website
  driver.get("https://www.lambdatest.com/automation-demos");
  // Initialize WebDriverWait with a timeout of 5 seconds
  WebDriverWait wait =new WebDriverWait(driver, Duration.ofSeconds(5));
  // ExpectedCondition for Presence of Element Located
  WebElement elementLocated = wait.until(ExpectedConditions.presenceOfElementLocated(By.id("username")));
  elementLocated.sendKeys("xyz@lambdatest");
  driver.findElement(By.id("password")).sendKeys("LambdaTest");
  // ExpectedCondition for Element to be Clickable
  WebElement clickableElement = wait.until(ExpectedConditions.elementToBeClickable(By.linkText("Blogs")));
  clickableElement.click();
  // ExpectedCondition for Visibility of Element Located
  WebElement visibleElement = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@id=\"menu-item-35\"]/a")));
  String elementText = visibleElement.getText();
  System.out.println(elementText);
 
  // ExpectedCondition for Visibility of All Elements Located
  List<WebElement> allVisibleElements = wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath("//*[@id=\"site-navigation\"]/div")));
  for (WebElement element : allVisibleElements) {
  System.out.println(element.getText());
  }
  // Close the browser
  driver.quit();
  }
}
```

In the above program, we started by importing the necessary modules and then created a WebDriver instance(e.g. ChromeDriver in our case) to navigate to our desired website.

![image](https://cdn-images-1.medium.com/max/800/0*4ec6d6UJCRa65ab0.png align="left")

Now, let’s look at the different *ExpectedConditions* methods used in the program above program.

**presenceOfElementLocated**: We waited for an element with the ID attribute “**username**” to be present in the DOM of the webpage. Once the element was found, it returned a reference to the WebElement, and we used the sendKeys method to input the text “**xyz@lambdatest**” into the corresponding input field. Similarly, we found the element with the ID attribute “**password**” and entered the text “**LambdaTest**” into the input field.

***A comprehensive*** [***end-to-end Testing***](https://www.lambdatest.com/learning-hub/end-to-end-testing?utm_source=devto&utm_medium=organic&utm_campaign=aug_21&utm_term=ap&utm_content=learning_hub) ***tutorial that covers what E2E Testing is, its importance, benefits, and how to perform it with real-time examples:.***

![image](https://cdn-images-1.medium.com/max/800/0*9O-xluuLqe2_YBRM.png align="left")

**elementToBeClickable**: This method waited for the element with the link text “**Blogs**” to become clickable. Once the element was clickable, it returned a reference to the WebElement, and we utilized the click method to navigate to the “Blogs” section.

![image](https://cdn-images-1.medium.com/max/800/0*Uoa43UFYLQ067XBc.png align="left")

![image](https://cdn-images-1.medium.com/max/800/0*bnkBjsQ2xkdGpG6m.png align="left")

**visibilityOfElementLocated**: We waited for an element with the specified XPath expression to become visible on the webpage. Once it became visible, the method returned the WebElement reference, and we extracted the text of the element and printed it.

![image](https://cdn-images-1.medium.com/max/800/0*t8JKjxBdio8CFuZZ.png align="left")

**visibilityOfAllElementsLocatedBy**: In this case, we waited for all elements matching the given XPath expression to be visible on the webpage. Once all elements were visible, the method returned a list of WebElement references. We then iterated through the list and printed the text of each element.

![image](https://cdn-images-1.medium.com/max/800/0*BGAbws1B7a9Q4Sid.png align="left")

### frameToBeAvailableAndSwitchToIt​ Method

This method is used to wait for a frame to be available on a web page and then switch the driver’s focus to that frame.

**Method Category** — ExpectedCondition&lt; WebDriver &gt;

Syntax-

```plaintext
ExpectedCondition<WebDriver> frameToBeAvailableAndSwitchToIt​(By locator)
```

### elementToBeSelected​ Method

This method is used to wait until the WebElement is selected with a specified locator. It is handy when you deal with web pages that involve user interactions, such as selecting options from dropdown menus, clicking checkboxes, or choosing radio buttons.

**Method Category** — ExpectedCondition&lt; Boolean &gt;

Syntax-

```plaintext
ExpectedCondition<Boolean> elementToBeSelected​(By locator)
```

### invisibilityOfElementLocated​ Method

This method is used to wait for a web element to become invisible or hidden on the web page before proceeding further. It continuously checks if the element is present in the DOM and visible on the page. If the element becomes invisible, it returns ‘**true**’, indicating that the element is no longer visible.

**Method Category** — ExpectedCondition&lt; Boolean &gt;

Syntax-

```plaintext
ExpectedCondition<Boolean> invisibilityOfElementLocated​(By locator)
```

### textToBe Method

This method is used to wait for the text of a web element to be equal to a given string (passes as a parameter) before proceeding further.

**Method Category** — ExpectedCondition

Syntax-

```plaintext
ExpectedCondition<Boolean> textToBe​(By locator, String text)
```

Let’s understand **textToBe** method with an example.

```plaintext
public class SeleniumWebDriverWaitExample {

 public static void main(String[] args) {
  WebDriver driver = new ChromeDriver();
  // Navigate to the website
  driver.get("https://www.lambdatest.com/automation-demos");
  // Initialize WebDriverWait with a timeout of 5 seconds
  WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(5));
  try {
  wait.until(ExpectedConditions.textToBe(By.xpath("//*[@id=\"newapply\"]/h2"), "Login Selenium Playground"));
  } catch (TimeoutException e) {
  // Handle the TimeoutException
  } finally {
  // Close the browser
  driver.quit();
  }
 }
}
```

In the above program, we use the Explicit Wait concept with Selenium *WebDriverWait* and *ExpectedConditions* **textToBe** method to wait for a specific element on the webpage to contain the given text “**Login Selenium Playground**”. Since the given text does not match the text located using the XPath expression in the specified time. Therefore a TimeoutException is caught, and the WebDriver is correctly closed after waiting for 5 seconds.

![image](https://cdn-images-1.medium.com/max/800/0*xMUsHdMr6ZK72udT.png align="left")

Now. we pass “**Login to Selenium Playground**” as a given text. In this case, the given text matches with the text located using the XPath expression. Therefore the WebDriver properly closed before 5 seconds.

```plaintext
public class SeleniumWebDriverWaitExample {

 public static void main(String[] args) {
  WebDriver driver = new ChromeDriver();
  // Navigate to the website
  driver.get("https://www.lambdatest.com/automation-demos");
  // Initialize WebDriverWait with a timeout of 5 seconds
  WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(5));
  try {
  wait.until(ExpectedConditions.textToBe(By.xpath("//*[@id=\"newapply\"]/h2"), "Login to Selenium Playground"));
  } catch (TimeoutException e) {
  // Handle the TimeoutException
  } finally {
  // Close the browser
  driver.quit();
  }
 }
}
```

***In this*** [***Appium***](https://www.lambdatest.com/appium?utm_source=devto&utm_medium=organic&utm_campaign=aug_21&utm_term=ap&utm_content=webpage) ***tutorial, learn about Appium and its benefits for mobile automation testing. Take a look at how Appium works and see how to perform Appium testing of your mobile applications.***

### textToBePresentInElementLocated​ Method

This method is used to check whether a given text (passed as a parameter to the method) is present in the visible text of a web element or not.

If the given text is present in the web element, it returns a boolean value ‘**true**’ or otherwise returns ‘**false**’.

**Method Category** — ExpectedCondition&lt; Boolean &gt;

Syntax-

```plaintext
ExpectedCondition<Boolean> textToBePresentInElementLocated​(By locator, String text)
```

Let’s understand the **textToBePresentInElementLocated​** method with an example.

```plaintext
public class SeleniumWebDriverWaitExample {

 public static void main(String[] args) {
  WebDriver driver = new ChromeDriver();
  // Navigate to the website
  driver.get("https://www.lambdatest.com/automation-demos");
  // Initialize WebDriverWait with a timeout of 5 seconds
  WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(5));
  // Wait for the element to contain the expected text
  wait.until(ExpectedConditions.textToBePresentInElementLocated(By.xpath("//*[@id=\"newapply\"]/h2"), "Selenium"));
  // Close the browser
  driver.quit();
 }
}
```

In this case, the given text “**Selenium**” matches with the text located using the XPath expression. Therefore the WebDriver properly closed before 5 seconds.

![image](https://cdn-images-1.medium.com/max/800/0*04td73UPIPnf00V7.png align="left")

### textToBePresentInElementValue​ Method

This method is used to check whether a given text (passed as a parameter to the method) is present in the specified elements value attribute or not.

If the given text is present, it returns a boolean value ‘**true**’ or otherwise returns ‘**false**’.

**Method Category** — ExpectedCondition&lt; Boolean &gt;

Syntax-

```plaintext
ExpectedCondition<Boolean> textToBePresentInElementValue​(By locator, String text)
```

### titleContains​ Method

This method is used to check whether a given title/text is present in the current page title or the title of a WebElement or not.

If the given text is present in the current page title, it returns a boolean value ‘**true**’ or otherwise returns ’**false**’.

**Method Category** — ExpectedCondition&lt; Boolean &gt;

Syntax-

```plaintext
ExpectedCondition<Boolean> titleContains​(String title)
```

Let’s understand the **titleContains** method with an example.

```plaintext
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.time.Duration;

public class SeleniumWebDriverWaitExample {

 public static void main(String[] args) {
  WebDriver driver = new ChromeDriver();
  // Navigate to the website
  driver.get("https://www.lambdatest.com/automation-demos");
  // Initialize WebDriverWait with a timeout of 5 seconds
  WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(5));
  boolean isTitleContains = false;
  try {
  wait.until(ExpectedConditions.titleContains("Selenium Playground"));
  isTitleContains = true;
  } catch (org.openqa.selenium.TimeoutException e) {
  isTitleContains = false;
  }
  // Print the result
  System.out.println("Is title contains 'Selenium Playground'? " + isTitleContains);
  // Close the browser
  driver.quit();
 }
}
```

Output:

```plaintext
Is title contains 'Selenium Playground'? true
```

![image](https://cdn-images-1.medium.com/max/800/0*bezkquayC-46RFK9.png align="left")

In this case, the given title “Selenium Playground” matches the title of the webpage. Therefore it returns true and the result is printed. (As you can see in the Output)

***A comprehensive*** [***UI testing***](https://www.lambdatest.com/learning-hub/ui-testing?utm_source=devto&utm_medium=organic&utm_campaign=aug_21&utm_term=ap&utm_content=learning_hub) ***tutorial that covers what UI testing is, its importance, benefits, and how to perform it with real-time examples.***

### titleIs​ Method

This method is used to check whether a web page title is exactly match with the given string(passed as a parameter) or not.

If the given text matches with the title of the webpage then it returns a boolean value ‘true’ or otherwise ‘false’.

**Method Category** — ExpectedCondition&lt; Boolean &gt;

Syntax-

```plaintext
ExpectedCondition<Boolean> titleIs​(String title)
```

### urlContains​ Method

This method is used to check whether a URL of a webpage contain a specific string or given string (passed as a parameter) or not.

If the given string is present in the URL then it returns a boolean value ‘true’ or otherwise ‘false’.

**Method Category** — ExpectedCondition&lt; Boolean &gt;

Syntax-

```plaintext
ExpectedCondition<Boolean> urlContains​(String fraction)
```

Let’s understand the **urlContains** method with an example.

```plaintext
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.time.Duration;
public class SeleniumWebDriverWaitExample {
 public static void main(String[] args) {
  WebDriver driver = new ChromeDriver();
  // Navigate to the website
  driver.get("https://www.lambdatest.com/automation-demos");
  // Initialize WebDriverWait with a timeout of 5 seconds
  WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(5));
  boolean isurlContains = false;
  try {
  wait.until(ExpectedConditions.urlContains("automation-demos"));
  isurlContains = true;
  } catch (org.openqa.selenium.TimeoutException e) {
  isurlContains = false;
  }
  // Print the result
  System.out.println("Is url contains 'automation-demos'? " + isurlContains);
  // Close the browser
  driver.quit();
 }
}
```

Output:

```plaintext
Is url contains 'automation-demos'? true
```

In this case, the URL of the webpage contains automation-demos. Therefore it returns true and the result is printed. (As you can see in the Output)

![image](https://cdn-images-1.medium.com/max/800/0*x5zs8HRK6n5KLfNI.png align="left")

Now, we passed the “xyz” and since the URL of the webpage didn’t contain “xyz”. Therefore it returns false and the result is printed. (As you can see in the Output)

```plaintext
public class SeleniumWebDriverWaitExample {

 public static void main(String[] args) {
  WebDriver driver = new ChromeDriver();
  // Navigate to the website
  driver.get("https://www.lambdatest.com/automation-demos");
  // Initialize WebDriverWait with a timeout of 5 seconds
  WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(5));
  boolean isurlContains = false;
  try {
  wait.until(ExpectedConditions.urlContains("xyz"));
  isurlContains = true;
  } catch (org.openqa.selenium.TimeoutException e) {
  isurlContains = false;
  }
  // Print the result
  System.out.println("Is url contains 'xyz'? " + isurlContains);
  // Close the browser
  driver.quit();
 }
}
```

Output:

```plaintext
Is url contains 'xyz'? false
```

### urlToBe​ Method

This method is used to check whether the URL of a web page exactly matches a specific URL/given URL or not.

If the given string exactly matches the URL of the webpage, it returns a boolean value ‘**true**’ or otherwise returns ‘**false**’.

**Method Category** — ExpectedCondition&lt; Boolean &gt;

Syntax-

```plaintext
ExpectedCondition<Boolean> urlToBe​(String url)
```

### alertIsPresent Method

This method is used to wait for an alert dialog to be present on a web page and then perform actions like accepting or dismissing the alert as part of your test flow. This method is particularly useful when dealing with web pages that use JavaScript-based alert boxes to show messages, prompts, or confirmations to the user.

**Method Category** — ExpectedCondition&lt; Alert &gt;

Syntax-

```plaintext
ExpectedCondition<Alert> alertIsPresent()
```

Let’s take an example for better understanding.

```plaintext
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.time.Duration;

public class SeleniumWebDriverWaitExample {

 public static void main(String[] args) {
  WebDriver driver = new ChromeDriver();
  // Navigate to the website
  driver.get("https://www.lambdatest.com/selenium-playground/javascript-alert-box-demo");
  driver.findElement(By.xpath("//*[@id=\"__next\"]/section[3]/div/div/div/div[1]/p/button")).click();
  // Initialize WebDriverWait with a timeout of 5 seconds
  WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(5));
  // Wait until an alert is present
  boolean isAlertPresent = false;
  try {
  wait.until(ExpectedConditions.alertIsPresent());
  isAlertPresent = true;
  } catch (org.openqa.selenium.TimeoutException e) {
  isAlertPresent = false;
  }
  // Print the result
  System.out.println("Is alert present? " + isAlertPresent);
  // If alert is present, handle it
  if (isAlertPresent) {
  Alert alert = driver.switchTo().alert();
  String alertText = alert.getText();
  System.out.println("Alert Text: " + alertText);
  // Accept the alert (Click OK)
  alert.accept();
  }
  // Close the browser
  driver.quit();
 }
}
```

Output:

```plaintext
Is alert present? true
Alert Text: Alert box!
```

In the above program, we use the Explicit Wait concept with Selenium WebDriverWait to check if an alert is present on a web page. It waits for a maximum of 5 seconds for the alert to appear. The result is then printed to the console, indicating whether the alert is present or not.  
If the alert is present, its text is retrieved and printed to the console. The alert is then accepted by clicking the “OK” button.

(As you can see in the image below)

![image](https://cdn-images-1.medium.com/max/800/0*H-jjXm1C5H9Pf_9x.png align="left")

![image](https://cdn-images-1.medium.com/max/800/0*_R5Vn_Ni2BcGU6P4.png align="left")

Finally, the code closes the web browser, ensuring smooth execution of the test regardless of the presence of the alert.

*You can also check out the article,* [*ExpectedConditions in Selenium*](https://www.lambdatest.com/blog/expected-conditions-in-selenium-examples/?utm_source=devto&utm_medium=organic&utm_campaign=aug_21&utm_term=ap&utm_content=blog)*, for more detailed information and related examples.*

***Run your*** [***Jest***](https://www.lambdatest.com/jest?utm_source=devto&utm_medium=organic&utm_campaign=aug_21&utm_term=ap&utm_content=webpage) ***automation tests in massive parallel across multiple browser and OS combinations with LambdaTest, Read more.***

{% youtube cgErlkHg_cI %}

If you would be interested in deep diving on the Wait Commands in Selenium, chekck out tutorial video on our [YouTube channel](https://www.youtube.com/@LambdaTest?sub_confirmation=1).

### Limitations of Selenium WebDriverWait

Selenium *WebDriverWait* is a class in Java used for handling synchronization automation testing. However, it does have some limitations. Let’s explore them.

* **Limited to Web-Based Applications**: Selenium WebDriverWait is specifically designed for web-based applications and cannot be used for other types of applications. For example — Mobile.
    
* **Dependency on Web Elements**: Selenium WebDriverWait relies on web elements to determine the synchronization condition. If the desired web element is not present or accessible, it can cause the wait to fail or result in a longer wait time.
    
* **Performance Impact**: Using Selenium WebDriverWait excessively or with long wait times can impact the performance of test execution. Therefore, it is important to find the right balance between wait times and test execution speed.
    
* **Difficulties with Dynamic Elements**: While Selenium WebDriverWait can handle some dynamic elements, it may encounter challenges with highly dynamic web pages where elements frequently change or are added/removed dynamically.
    
* **Lack of Native Support for Asynchronous Operations**: Selenium WebDriverWait may not handle all types of asynchronous operations or AJAX requests by default. Additional customization may be required to handle such scenarios.
    

### Conclusion

In this article, we have explored the concept of Explicit Wait using the Selenium WebDriverWait class in Java. We have introduced WebDriverWait and discussed its advantages. Next, we dived into the Explicit Waits using the WebDriverWait class. After that, we discussed *ExpectedConditions* available in Selenium Java and provided detailed explanations with real-world examples to enhance your understanding. We have addressed some limitations associated with using Explicit Waits in Selenium.

Our primary goal with this article is to offer a comprehensive and reader-friendly resource that equips you with the knowledge and guidance needed to implement WebDriverWait in your Selenium test automation projects effectively.