Generally selenium WebDriver handles page loading or wait for page to load by It self If you have used Implicit Wait In your test. But many on development sites have a page loading Issues and It Is taking more or less time for page to load on every test iteration. So some times your test will run without any Issue and some times It will be unable to found some elements due to the page loading Issue.
I have a solution for such Issue If any one facing It. We can use bellow given javascript syntax In our test to check (loading) status of page. It will return "complete" when page Is loaded completely.
document.readyState
We have already learnt how to execute javascript In selenium test earlier.You will find few of the examples on THIS LINK. Javascript execution syntax to get page loading status In webdriver Is as bellow. It will check Page ready status for us.
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("return document.readyState").toString().equals("complete");
So we can check page ready status after every 1 second using for loop as shown In bellow example.
Once page Is ready, It will start taking actions on page.
package Testing_Pack;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class checkPageReady {
WebDriver driver;
@BeforeTest
public void setup() throws Exception {
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("http://only-testing-blog.blogspot.in/2014/04/calc.html");
}
@Test
public void calc() {
//Call this function to wait for page to ready.
checkPageIsReady();
//Once page Is ready/loaded, Bellow given steps will be executed.
driver.findElement(By.xpath("//input[@id='1']")).click();
driver.findElement(By.xpath("//input[@id='plus']")).click();
driver.findElement(By.xpath("//input[@id='5']")).click();
driver.findElement(By.xpath("//input[@id='equals']")).click();
}
public void checkPageIsReady() {
JavascriptExecutor js = (JavascriptExecutor)driver;
//Initially bellow given if condition will check ready state of page.
if (js.executeScript("return document.readyState").toString().equals("complete")){
System.out.println("Page Is loaded.");
return;
}
//This loop will rotate for 25 times to check If page Is ready after every 1 second.
//You can replace your value with 25 If you wants to Increase or decrease wait time.
for (int i=0; i<25; i++){
try {
Thread.sleep(1000);
}catch (InterruptedException e) {}
//To check page ready state.
if (js.executeScript("return document.readyState").toString().equals("complete")){
break;
}
}
}
}
This way, You can check or wait for page to load In selenium webdriver test.
No comments:
Post a Comment