How I can check whether a page is loaded completely or not in web driver?
Solution 1:
Selenium does it for you. Or at least it tries its best. Sometimes it falls short, and you must help it a little bit. The usual solution is Implicit Wait
which solves most of the problems.
If you really know what you're doing, and why you're doing it, you could try to write a generic method which would check whether the page is completely loaded. However, it can't be done for every web and for every situation.
Related question: Selenium WebDriver : Wait for complex page with JavaScript(JS) to load, see my answer there.
Shorter version: You'll never be sure.
The "normal" load is easy - document.readyState
. This one is implemented by Selenium, of course. The problematic thing are asynchronous requests, AJAX, because you can never tell whether it's done for good or not. Most of today's webpages have scripts that run forever and poll the server all the time.
The various things you could do are under the link above. Or, like 95% of other people, use Implicit Wait
implicity and Explicit Wait
+ ExpectedConditions
where needed.
E.g. after a click, some element on the page should become visible and you need to wait for it:
WebDriverWait wait = new WebDriverWait(driver, 10); // you can reuse this one
WebElement elem = driver.findElement(By.id("myInvisibleElement"));
elem.click();
wait.until(ExpectedConditions.visibilityOf(elem));
Solution 2:
Simple ready2use snippet, working perfectly for me
static void waitForPageLoad(WebDriver wdriver) {
WebDriverWait wait = new WebDriverWait(wdriver, 60);
Predicate<WebDriver> pageLoaded = new Predicate<WebDriver>() {
@Override
public boolean apply(WebDriver input) {
return ((JavascriptExecutor) input).executeScript("return document.readyState").equals("complete");
}
};
wait.until(pageLoaded);
}
Solution 3:
You can set a JavaScript variable in your WepPage that gets set once it's been loaded. You could put it anywhere, but if you're using jQuery, $(document).onReady
isn't a bad place to start. If not, then you can put it in a <script>
tag at the bottom of the page.
The advantage of this method as opposed to checking for element visibility is that you know the exact state of the page after the wait
statement executes.
MyWebPage.html
... All my page content ...
<script> window.TestReady = true; </script></body></html>
And in your test (C# example):
// The timespan determines how long to wait for any 'condition' to return a value
// If it is exceeded an exception is thrown.
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(5.0));
// Set the 'condition' as an anonymous function returning a boolean
wait.Until<Boolean>(delegate(IWebDriver d)
{
// Check if our global variable is initialized by running a little JS
return (Boolean)((IJavaScriptExecutor)d).ExecuteScript("return typeof(window.TestReady) !== 'undefined' && window.TestReady === true");
});