W3docs

Wait for page load in Selenium

In Selenium, you can use the WebDriverWait class to wait for a page to load.

In Selenium, driver.get() blocks execution until the page finishes loading, so explicit waits for page load are typically unnecessary. To wait for a specific condition after the page loads, such as an element becoming visible, you can use the WebDriverWait class.

Here is an example of how to wait for an element to load in Java:


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

WebDriver driver = new ChromeDriver();
driver.get("http://www.example.com");

// Wait for the element to be visible, timeout after 10 seconds
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("some-element-id")));

// Element is loaded, do something here

This will wait up to 10 seconds for the element with ID "some-element-id" to be visible. If the element becomes visible before the timeout, the script continues execution. If the timeout is reached and the element is still not visible, a TimeoutException will be thrown.

You can also use other ExpectedConditions to wait for different DOM events, such as the presence of an element, the absence of an element, or the text of an element to match a certain value. If you specifically need to synchronize with the browser's page load state, you can use ExpectedConditions.documentReadyState("complete") or `ExpectedConditions.pageLoadState(PageLoadState.NORMAL)` (Selenium 4.13+).