How to wait until an element is present in Selenium?


We can wait until an element is present in Selenium Webdriver. This can be done with the help of synchronization concept. We have an explicit wait condition where we can pause or wait for an element before proceeding to the next step.

The explicit wait waits for a specific amount of time before throwing an exception. To verify if an element is present, we can use the expected condition presenceOfElementLocated.

Example

Code Implementation.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class ElementPresenceWait{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url = "https://www.tutorialspoint.com/about/about_careers.htm";
      driver.get(url);
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      // identify element and click()
      WebElement l=driver.findElement(By.linkText("Terms of Use"));
      l.click();
      // explicit wait condition
      WebDriverWait w = new WebDriverWait(driver,3);
      // presenceOfElementLocated condition
      w.until(ExpectedConditions.presenceOfElementLocated (By.cssSelector("h1")));
      // get text of element and print
      System.out.println("Element present having text:" + l.getText());
      driver.quit()
   }
}

Output

Updated on: 15-Sep-2023

25K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements