Need Selenium to wait until the document is ready

SeleniumAutomation TestingTesting Tools

We can wait until the document is ready (page loaded completely) in Selenium by applying the method pageLoadTimeout. The wait time is passed as a parameter to this method.

The webdriver waits for this duration for the page to load completely. If this time gets elapsed without page loading, a TimeoutException is thrown.

Syntax

driver.manage().timeouts().pageLoadTimeout(3, TimeUnit.SECONDS);

Example

Code Implementation with pageLoadTimeout

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class PageLdTime{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",
         "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      //page load wait
      driver.manage().timeouts().pageLoadTimeout(3, TimeUnit.SECONDS);
      //URL launch
      driver.get("https://www.tutorialspoint.com/index.htm");
      driver.close();
   }
}

We can also wait until the document is ready (page loaded completely) by using the JavaScript Executor. The wait is till the JavaScript commanddocument.readyState returns complete.

Syntax

JavascriptExecutor j = (JavascriptExecutor)driver;
j.executeScript("return document.readyState").toString().equals("complete");

Code Implementation with JavaScript Executor

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;
public class PageldJs{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",
         "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL launch
      driver.get("https://www.tutorialspoint.com/index.htm");
      try{
         // Javascript Executor for ready state
         JavascriptExecutor j = (JavascriptExecutor)driver;
         if (j.executeScript("return document.readyState").toString().equals("complete")){
            System.out.println("Page in ready state"); }
         } catch(Exception exe) {
            System.out.println("Page not in ready state");
         }
         driver.close();
      }
   }
}

Output

raja
Published on 06-Apr-2021 11:43:37
Advertisements