How to Set Page Load Timeout in Selenium WebDriver
In Selenium WebDriver, you set the page load timeout using
driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(seconds)). This tells Selenium how long to wait for a page to load before throwing an error.Syntax
The syntax to set page load timeout in Selenium WebDriver is:
driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(seconds))
Here, driver is your WebDriver instance, and seconds is the maximum time to wait for the page to load.
java
driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(30));Example
This example shows how to set a 20-second page load timeout in Selenium using Java. If the page does not load within 20 seconds, a TimeoutException will be thrown.
java
import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import java.time.Duration; public class PageLoadTimeoutExample { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); WebDriver driver = new ChromeDriver(); // Set page load timeout to 20 seconds driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(20)); try { driver.get("https://example.com"); System.out.println("Page loaded successfully."); } catch (org.openqa.selenium.TimeoutException e) { System.out.println("Page load timed out after 20 seconds."); } finally { driver.quit(); } } }
Output
Page loaded successfully.
Common Pitfalls
- Setting the timeout too low can cause tests to fail if pages load slowly.
- Not using
Duration.ofSeconds()(older Selenium versions used milliseconds) can cause errors. - Confusing
pageLoadTimeoutwith implicit or script timeouts. - Forgetting to handle
TimeoutExceptioncan crash tests unexpectedly.
java
/* Wrong way: Using integer instead of Duration */ driver.manage().timeouts().pageLoadTimeout(20); // This will not compile in Selenium 4 /* Right way: Use Duration */ driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(20));
Quick Reference
| Method | Description |
|---|---|
| pageLoadTimeout(Duration.ofSeconds(x)) | Sets max time to wait for page load |
| implicitlyWait(Duration.ofSeconds(x)) | Sets max time to wait for element presence |
| scriptTimeout(Duration.ofSeconds(x)) | Sets max time to wait for async scripts |
Key Takeaways
Use driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(seconds)) to set page load timeout.
Always use Duration.ofSeconds() with Selenium 4 and above for timeouts.
Handle TimeoutException to manage page load failures gracefully.
Do not confuse page load timeout with implicit or script timeouts.
Set a reasonable timeout value to balance test speed and reliability.