Selenium Wait Until Element is Visible

Profile picture for user arilio666

We can wait for an element until its visibility and do some action using a simple synchronization concept. In selenium, using the explicit wait condition, we can pause or wait for an element before proceeding to the following step of the code.

Explicit wait waits for some time before throwing an exception. presenceOfElementLocated can is used to verify if the element is visible or not.

Example:

We will be using the programsbuzz site and clicking on contacts after its load time and when it is visible.

public static void main(String[] args) throws Throwable {
        WebDriverManager.chromedriver().setup();
        ChromeDriver driver = new ChromeDriver();
        driver.get("https://www.programsbuzz.com");
        driver.manage().window().maximize();
        WebDriverWait w = new WebDriverWait(driver, 3);
        w.until(ExpectedConditions
                .presenceOfElementLocated(By.xpath("//a[@class='we-mega-menu-li'][normalize-space()='Contact']")));
        driver.findElement(By.xpath("//a[@class='we-mega-menu-li'][normalize-space()='Contact']")).click();
    }
}
  • We have used the expected conditions to wait for the presenceOfElementLocated.
  • This takes the locator to be waited for, and then after we click on it.
  • So this is how we can wait for elements to be visible before interacting with them.