How to get Selenium to wait for a page to load

Learn how to get Selenium Wait for a page to load using implicit wait, explicit wait, and fluent wait.

Get Started free
How-to-get-Selenium-to-wait-for-a-page-to-load
Home Guide How to get Selenium to wait for a page to load

How to get Selenium to wait for a page to load

QA teams should ensure that Selenium waits properly before going forward with actions like clicks or form submissions to simulate real user behavior. Even though Selenium Webdriver typically waits for the DOM to load before proceeding to the next step, extra waits are necessary in scenarios like:

  • Dynamic or Ajax-loaded elements that appear after the initial page load.
  • Elements present in the DOM but take time to be visible or interactable (e.g., a dropdown loading values after a user action).

To handle such scenarios, you can use Wait commands in Selenium. In this guide, learn what are Waits in Selenium, How to implement Selenium Wait for page to load and more.

Importance of Page Load in Selenium

A page load is the process of a web page being fetched from the server and fully rendered in the browser. This includes HTML, CSS, JavaScript, and all related resources like images and fonts. Here is why page load is important in Selenium:

  • Page loads ensure the availability of elements before interaction, thus preventing test failures.
  • It ensures synchronization between test steps and application behavior.
  • Proper handling of page loads help spot performance issues like slow or incomplete page loads.
  • It improves test reliability while working with dynamic or Ajax-loaded content.
  • Reflects real user behavior

How to implement Selenium wait for page to load

Selenium Wait commands instruct a test to pause for a predetermined length of time before moving onto the next step in the script. The pause lets the page load and the web elements become visible/present/populated/clickable before WebDriver can interact with them and proceed with the test.

Wait commands are beneficial because Selenium will throw an Element Not Visible Exception if it cannot locate the element required for the test to run. With wait commands, the test will wait for the element to become available, thus preventing the exception from showing up.

There are three ways to implement Selenium wait for page to load:

  • Using Implicit Wait
  • Using Explicit Wait
  • Using Fluent Wait

Using Implicit Wait

The Implicit Wait tells WebDriver to wait a specific amount of time (say, 30 seconds) before proceeding with the next step. If the tester knows how much time the page and element will take to load, they should use Implicit Wait.

Let’s say a website under test takes ten seconds to load a page until a particular element shows up. In that case, set implicit wait for 10 seconds. The test will pause, and once the time passes, Webdriver will continue to run the script as planned.

WebDriver driver => new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("https://url_that_delays_loading");
WebElement myDynamicElement = driver.findElement(By.id("myDynamicElement"));

Note that the Implicit Wait function will be applicable as long as the current browser is open. That means all elements being searched for by the Selenium script will take the time laid out in the Implicit Wait.

Using Explicit Wait

The Explicit Wait is more advanced in its functioning. It instructs WebDriver to pause a test until a predetermined condition is fulfilled.

Let’s say the website under test has a feature displaying a pop-up. The user has to enter some data, following which a pop-up appears. This feature needs to be tested in this exact sequence, including the time taken for the user to input data, server response time, etc.

In this case, the Explicit Wait will wait for the pop-up to appear before proceeding with the test. However, since the test cannot wait an infinite amount of time, testers also insert a duration for WebDriver to pause before carrying on.

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Firefox()
driver.get("http://www.example.com") #This is a dummy website URL
try:
elem = WebDriverWait(driver, 30).until(
EC.presence_of_element_located((By.ID, "Element_to_be_found")) #This is a dummy element
)
finally:
driver.quit()

The code will instruct WebDriver to wait for 30 seconds. If the specified condition is met before that, the test will proceed, If not, it will wait the whole 30 seconds before moving forward.

In order to declare an explicit wait, one has to use “ExpectedConditions”. The following Expected Conditions in Selenium can be used in Explicit Wait:

  • alertIsPresent()
  • elementSelectionStateToBe()
  • elementToBeClickable()
  • elementToBeSelected()
  • frameToBeAvaliableAndSwitchToIt()
  • invisibilityOfTheElementLocated()
  • invisibilityOfElementWithText()
  • presenceOfAllElementsLocatedBy()
  • presenceOfElementLocated()
  • textToBePresentInElement()
  • textToBePresentInElementLocated()
  • textToBePresentInElementValue()
  • titleIs()
  • titleContains()
  • visibilityOf()
  • visibilityOfAllElements()
  • visibilityOfAllElementsLocatedBy()
  • visibilityOfElementLocated()

Talk to an Expert

Using Fluent Wait

The Fluent Wait is an advancement on the Explicit Wait. Using it, testers can define a specific condition and the frequency for which WebDriver should check for the condition to appear in a particular length of time.

Let’s say the website under test includes some elements that load dynamically. The tester knows it takes a total of 5 seconds to load, not more. But it can become visible anytime between zero to five seconds.

In this case, Fluent Wait comes to the rescue. The tester can use it to instruct Selenium WebDriver to keep checking on the element at regular intervals.

//Declare and initialise a fluent wait
FluentWait wait = new FluentWait(driver);
//Specify the timout of the wait
wait.withTimeout(5000, TimeUnit.MILLISECONDS);
//Specify polling time
wait.pollingEvery(250, TimeUnit.MILLISECONDS);
//Specify what exceptions to ignore
wait.ignoring(NoSuchElementException.class)

//This is how we specify the condition to wait on.
wait.until(ExpectedConditions.alertIsPresent());

Fluent Wait operates with two main parameters: timeout value and polling frequency. The code defines timeout value as 5 seconds and polling frequency as 0.25 seconds. That means WebDriver will wait no more than 5 seconds to verify the specified condition. If the condition occurs (the element populates) during 5 seconds, it will move on to the next step in the test script. If not, it will return “ElementNotVisibleException”.

Handling Asynchronous Page Loads

Web applications can load content asynchronously using JavaScript or Ajax. This implies that parts of the page may proceed to load or update after the initial DOM load is done. Selenium WebDriver does not automatically wait for these asynchronous events, that could lead tests to fail if elements don’t fully load or  are visible.

You can manage such cases by:

  • Using Explicit Waits to wait for specific conditions (e.g., element visibility, clickability).
  • Waiting for Ajax calls to be done by checking for indicators such as loading spinners or particular DOM changes.
  • Avoiding the use of fixed delays (Thread.sleep()) as they are unreliable and can slow down tests.

QA teams should strategically leverage Wait commands to ensure the scripts interact with the page only when it’s actually ready.

Common Challenges with Page Load and Selenium

Here are the challenges of page load and Selenium and the corresponding solutions:

1. Interacting with elements before they load

Solution: Use Explicit Waits like visibilityOfElementLocated

2. Handling dynamic/Ajax content

Solution: Wait for specific conditions or DOM changes

3. Test failures because of inconsistent load times

Solution: Execute Fluent Waits with timeout and polling frequency

4. Overuse of Thread.sleep() resulting in slow, flaky tests

Solution: Replace with smart waits (Implicit or Explicit)

BrowserStack Automate Banner

Conclusion

Using Selenium Wait for page to load is quite necessary for automated Selenium testing since it is a common occurrence in everyday internet users’ browsing journey. Selenium Wait commands are exceptionally effective in doing so, and implementing them is fairly uncomplicated, making Browser Automation seamless, as the examples above have demonstrated.

Selenium Waits help detect and debug issues that may occur due to variations in time lag. However, for the results of these commands to be 100% accurate all the time, they must be run on real browsers and devices.

BrowserStack’s cloud Selenium grid offers 3500+ real devices and browsers for automated testing. That means users can run tests on multiple real devices and browsers by simply signing up, logging in, and selecting the required combinations.

Run Selenium Tests on Real Browsers Free

Frequently Asked Questions

1. How to wait for 30 seconds in Selenium?

You can use Explicit wait to wait for 30 seconds in Selenium:

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(30));

wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("elementId")));

2. How to change the default timeout in Selenium

You can adjust the implicit wait to change the default timeout in Selenium

Global timeout for all element searches with implicit wait:

driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(30));

Here, you can customize the waiting time according to your test requirements.

Useful Resources for Selenium

Methods, Classes, and Commands

Configuration

XPath

Locators and Selectors

Waits in Selenium

Frameworks in Selenium

Miscellaneous

Best Practices, Tips and Tricks

Design Patterns in Selenium: Page Object Model and Page Factory

Action Class

TestNG and Selenium

JUnit and Selenium

Use Cases

Types of Testing with Selenium

Tags
Selenium Selenium Webdriver

Get answers on our Discord Community

Join our Discord community to connect with others! Get your questions answered and stay informed.

Join Discord Community
Discord