Wait for Page Load in Selenium

Wait for Page Load in Selenium

In this tutorial, we will learn how to wait for a page to load in Selenium before interacting with the web elements present on that page in order to avoid NoSuchElementException.

Before going further into the implementation of wait till page load in Selenium you need to understand the following points-

  • An element that triggers page load waits until the DOM gets loaded before returning control to the driver.
    For example – if we submit a form by clicking the Submit button then the next statement after the submit button click operation will be attempted by WebDriver only after the page gets loaded completely. So, in most cases, we don’t even have to wait for the page to load.
  • We may have to introduce a wait time when dealing with elements that are ajax based or dynamic elements that load even after the page load.
  • In certain cases, we deal with elements that may be visible on page load or after some trigger action but take some time to be available for interaction.
    For example, a dropdown with dynamic values may be available on the DOM throughout but have its values populated only after we perform some action based on which the corresponding values get dynamically populated.
    So, in this case, if we try to select a particular value, we must wait for some time for the element to be available for interaction.

Wait for the page to load Implementation

Selenium Webdriver doesn’t provide any inherent support for wait till page load implementation. But we can make use of Explicit Waits to achieve the desired outcome. For this, we need to identify the element on the webpage that’s the last one to load or become available for interaction.

Now, we need to use the explicit wait with the appropriate Expected condition like “ElementToBeClickable” for page load implementation. Thus, making sure that the driver waits till all the web elements get loaded successfully before attempting to interact with them.

WebDriverWait wait = new WebDriverWait(driver, 20);

От QA genius