How do you get selenium to recognize that a page loaded?

Software TestingAutomation TestingSelenium Web Driver

We can get Selenium to recognize that a page is loaded. We can set the implicit wait for this purpose. It shall make the driver to wait for a specific amount of time for an element to be available after page loaded.

Syntax

driver.manage().timeouts().implicitlyWait();

After the page is loaded, we can also invoke Javascript method document.readyState and wait till complete is returned.

Syntax

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

After this, verify if the URL matches the one we are looking for.

Example

Code Implementation with implicit wait.

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;
public class Pageload{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",
      "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url = "https://www.tutorialspoint.com/index.htm";
      driver.get(url);
      // wait of 12 seconds
      driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);
      // identify element, enter text
      WebElement m=driver.findElement(By.id("gsc-i-id1"));
      m.sendKeys("Selenium");
   }
}

Example

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 PagaLoadJS{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",
      "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url = "https://www.tutorialspoint.com/index.htm";
      driver.get(url);
      // Javascript executor to return value
      JavascriptExecutor j = (JavascriptExecutor) driver;
      j.executeScript("return document.readyState")
      .toString().equals("complete");
      // get the current URL
      String s = driver.getCurrentUrl();
      // checking condition if the URL is loaded
      if (s.equals(url)) {
         System.out.println("Page Loaded");
         System.out.println("Current Url: " + s);
      }
      else {
         System.out.println("Page did not load");
      }
      driver.quit();
   }
}

Output

raja
Published on 28-Nov-2020 13:38:01
Advertisements