How do you make Selenium 2.0 wait for the page to load?

- 30,738
- 21
- 105
- 131

- 3,021
- 2
- 15
- 4
-
8To me only [Paul's](http://stackoverflow.com/a/5876462/705773) answer look correct, most of the highly voted answer talks about waiting for a particular element. – Ajinkya Oct 22 '14 at 04:52
-
See also: [load - Selenium wait until document is ready - Stack Overflow](https://stackoverflow.com/questions/15122864/selenium-wait-until-document-is-ready/15124562#15124562) and [Python Selenium - Wait until next page has loaded after form submit - Stack Overflow](https://stackoverflow.com/questions/42069503/python-selenium-wait-until-next-page-has-loaded-after-form-submit) – user202729 Dec 09 '21 at 08:40
48 Answers
You can also check pageloaded using following code
IWait<IWebDriver> wait = new OpenQA.Selenium.Support.UI.WebDriverWait(driver, TimeSpan.FromSeconds(30.00));
wait.Until(driver1 => ((IJavaScriptExecutor)driver).ExecuteScript("return document.readyState").Equals("complete"));
-
40You would think something like this would be built in. Waiting for page loads is a pretty common thing on the web. – PRMan Dec 31 '14 at 18:03
-
24does this really work all the time? Maybe Im missing something from your code but you are waiting for the dom to be in ready state. But consider that if your code executes too fast the previous page might not be unloaded yet and it will return true even though you are still on the old page. What you need to do is wait for the current page to unload and then call your above code. A way to detect page unload is to get a webelement on the current page and wait till it becomes stale. http://www.obeythetestinggoat.com/how-to-get-selenium-to-wait-for-page-load-after-a-click.html – George Feb 06 '15 at 17:38
-
8FYI - Even still the above does not guarentee that the page is complete - just that the dom is ready. Any dojo/jquery might still be dynamically building elements on the page so you might need first wait for dynamic elements before interacting with them. – George Feb 06 '15 at 17:39
-
1@Imran have you seen a similar approach but for Python? – AdjunctProfessorFalcon Jul 11 '15 at 01:35
-
3Be aware that this method only checks the DOM. If you use Ajax or AngularJS, this will not work because there will be some asynchronous calls that cannot be detected by the document.readyState. – Homewrecker Aug 28 '15 at 07:46
-
I cannot get it compiling, though I think I have imported all dependencies, I get compiler error `[ERROR] /C:/Source/Website_auticon_mvn/all_links/src/test/java/de/auticon/website/AppTest.java:[127,47] illegal start of expression`. – Leder Oct 29 '18 at 10:45
-
Where do you get `OpenQA.Selenium.Support.UI.WebDriverWait` and `IWait` from? – Kingamere Feb 17 '19 at 23:13
-
12This is C# code. This does not work with Java, and the question asked about *Java*. – Kingamere Feb 18 '19 at 15:47
-
2For anybody curious, [here is a permalink (`WaitForPageToLoad.java` L93)](https://github.com/SeleniumHQ/selenium/blob/0e493305c2c7064f2b9517c4c1de91fb1fdb0f64/java/client/src/com/thoughtworks/selenium/webdriven/commands/WaitForPageToLoad.java#L93) to the location in the Selenium Java client which automatically waits for the page to load as part of its existing implementation (which does indeed check for `document.readyState`). – George Pantazes Mar 04 '19 at 20:29
-
Does not work for 'TextPage': Error: 'Cannot execute JS against a plain text page' – Cengiz Sep 24 '19 at 13:20
-
I posted an answer https://stackoverflow.com/questions/18486511/selenium-webdriver-how-to-wait-for-iframes-to-load-completely/59060172#59060172 Generally you want an element to go stale and then wait for a new element to load – Archmede Nov 26 '19 at 22:20
Use class WebDriverWait
Also see here
You can expect to show some element. something like in C#:
WebDriver _driver = new WebDriver();
WebDriverWait _wait = new WebDriverWait(_driver, new TimeSpan(0, 1, 0));
_wait.Until(d => d.FindElement(By.Id("Id_Your_UIElement")));

- 17,541
- 8
- 92
- 91

- 2,401
- 2
- 17
- 7
-
-
what is that TimeSpan mean, as we should create a method like timespan or its an inbuilt method? – Emmanuel Angelo.R Apr 14 '14 at 05:12
-
3@EmmanuelAngelo.R [TimeSpan](http://msdn.microsoft.com/en-us/library/system.timespan.aspx) is a .Net data structure. – rjzii Apr 23 '14 at 14:34
-
26
-
4This will work to wait for loading of a particular element and not for whole page. – Ajinkya Oct 22 '14 at 04:49
-
@xyz ... you are mistaken. If you evolve your code and use the ExpectedConditions class, you can do this in: `JavaWebDriverWait wait = new WebDriverWait(driver, 10);` `wait.until(ExpectedConditions.visibilityOfAllElements(list));` where list is an arraylist of elements – Mario Galea Jan 19 '16 at 14:52
-
2This does not guarantee at all that an element will be fully loaded neither answers the question. How can anyone upvote to this ? – Boris D. Teoharov Nov 23 '17 at 17:55
If you set the implicit wait of the driver, then call the findElement
method on an element you expect to be on the loaded page, the WebDriver will poll for that element until it finds the element or reaches the time out value.
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
source: implicit-waits
-
7
-
It mean that it will try something during 10 seconds, before it raise exception. so it can't make sure that it will take 10 seconds delay. – skysign Jul 23 '16 at 09:06
-
1
-
@testerjoe2 it waits till particular element is found, question is about how to wait for page load. – Ajinkya Nov 11 '16 at 09:07
In general, with Selenium 2.0 the web driver should only return control to the calling code once it has determined that the page has loaded. If it does not, you can call waitforelemement
, which cycles round calling findelement
until it is found or times out (time out can be set).

- 30,738
- 21
- 105
- 131

- 6,088
- 2
- 35
- 56
-
2Adding to Paul's answer. Please check this also http://stackoverflow.com/questions/5858743/driver-wait-throws-illegalmonitorstateexception/5865445#5865445. – 9ikhan May 04 '11 at 03:56
-
31Unfortunately, Selenium 2 doesn't wait in all cases for a page to load. For example WebElement:click() doesn't wait and this is explicitly said in the belonging Javadoc. However, they don't tell how I can check for a new page to be loaded. `If click() causes a new page to be loaded via an event or is done by sending a native event (which is a common case on Firefox, IE on Windows) then the method will not wait for it to be loaded and the caller should verify that a new page has been loaded.` – Sebi Sep 28 '11 at 09:20
-
From [doc](http://selenium.googlecode.com/git/docs/api/java/org/openqa/selenium/WebDriver.html#get%28java.lang.String%29) _..and the method will block until the load is complete..._ – Ajinkya Oct 22 '14 at 04:54
-
2@Karna: Yes, in theory it should always and in practise it did most of the time. Using Selenium at the time highlighted that there were times when it thought the page had finished loading but it hadn't. I've not used selenium much recently so this may or may not still be the case. – Paul Hadfield Oct 22 '14 at 10:20
-
It is still same. Commented to support your answer. See my comment on question – Ajinkya Oct 22 '14 at 11:20
-
3I agree : especially internet explorer driver is buggy and returns control immediately in some cases even though a page is still loading. It my case, I added a wait using `JavascriptExecutor` , waiting for document.readyState to be "complete". Because of the round trip from selenium to the browser, the race condition is mitigated I guess, and this "always" works for me. After "click()" when I expect a page to load, I explicitly wait (using WebDriverWait) for the readystate. ] – dmansfield May 08 '15 at 13:40
Ruby implementation:
wait = Selenium::WebDriver::Wait.new(:timeout => 10)
wait.until {
@driver.execute_script("return document.readyState;") == "complete"
}

- 30,738
- 21
- 105
- 131

- 27,270
- 18
- 89
- 122
-
20Python equivalent: WebDriverWait(driver, 10).until(lambda d: d.execute_script('return document.readyState') == 'complete') – blaze Jan 15 '14 at 20:33
-
5Python use the above code but don't forget to this line..| from selenium.webdriver.support.ui import WebDriverWait – t3dodson Jul 26 '14 at 19:48
-
I had a problem clicking on an element when the page was not fully loaded. In Python i tried time.sleep(30). It worked. It will always wait for the max 30 secs though. I then tried the following code and it is more efficient now, quicker. WebDriverWait(driver, 10).until(lambda d: driver.find_element_by_xpath("//div[. = 'Administration']").click()) – Riaz Ladhani May 11 '15 at 13:17
You may remove the System.out
line. It is added for debug purposes.
WebDriver driver_;
public void waitForPageLoad() {
Wait<WebDriver> wait = new WebDriverWait(driver_, 30);
wait.until(new Function<WebDriver, Boolean>() {
public Boolean apply(WebDriver driver) {
System.out.println("Current Window State : "
+ String.valueOf(((JavascriptExecutor) driver).executeScript("return document.readyState")));
return String
.valueOf(((JavascriptExecutor) driver).executeScript("return document.readyState"))
.equals("complete");
}
});
}

- 30,738
- 21
- 105
- 131

- 274
- 2
- 4
-
Thanks for this tips. I add it in my SeleniumHelper; cf. [javabox](https://github.com/boly38/javabox) – boly38 Jun 20 '14 at 09:51
All of these solutions are OK for specific cases, but they suffer from at least one of a couple of possible problems:
They are not generic enough -- they want you to know, ahead of time, that some specific condition will be true of the page you are going to (eg some element will be displayed)
They are open to a race condition where you use an element that is actually present on the old page as well as the new page.
Here's my attempt at a generic solution that avoids this problem (in Python):
First, a generic "wait" function (use a WebDriverWait if you like, I find them ugly):
def wait_for(condition_function):
start_time = time.time()
while time.time() < start_time + 3:
if condition_function():
return True
else:
time.sleep(0.1)
raise Exception('Timeout waiting for {}'.format(condition_function.__name__))
Next, the solution relies on the fact that selenium records an (internal) id-number for all elements on a page, including the top-level <html>
element. When a page refreshes or loads, it gets a new html element with a new ID.
So, assuming you want to click on a link with text "my link" for example:
old_page = browser.find_element_by_tag_name('html')
browser.find_element_by_link_text('my link').click()
def page_has_loaded():
new_page = browser.find_element_by_tag_name('html')
return new_page.id != old_page.id
wait_for(page_has_loaded)
For more Pythonic, reusable, generic helper, you can make a context manager:
from contextlib import contextmanager
@contextmanager
def wait_for_page_load(browser):
old_page = browser.find_element_by_tag_name('html')
yield
def page_has_loaded():
new_page = browser.find_element_by_tag_name('html')
return new_page.id != old_page.id
wait_for(page_has_loaded)
And then you can use it on pretty much any selenium interaction:
with wait_for_page_load(browser):
browser.find_element_by_link_text('my link').click()
I reckon that's bulletproof! What do you think?
More info in a blog post about it here

- 15,359
- 7
- 71
- 70
-
I read your web page before searching again more specifically for java code which implements your solution. Nothing so far... – andrew lorien Aug 09 '16 at 07:47
Here is a Java 8 version of the currently most upvoted answer:
WebDriverWait wait = new WebDriverWait(myDriver, Duration.ofSeconds(15));
wait.until(webDriver -> "complete".equals(((JavascriptExecutor) webDriver)
.executeScript("return document.readyState")));
Where myDriver
is a WebDriver
object (declared earlier).
Note: Be aware that this method (document.readyState
) only checks the DOM.

- 39,162
- 17
- 99
- 152

- 435
- 6
- 17
-
1`WebDriverWait(drive, long)` is deprecated so use `WebDriverWait(drive, duration)` ex:- `import java.time.Duration; WebDriverWait(driver, Duration.ofSeconds(5));` – Isuru Dilshan Jan 15 '21 at 16:36
You can also use the class: ExpectedConditions
to explicitly wait for an element to show up on the webpage before you can take any action further actions
You can use the ExpectedConditions
class to determine if an element is visible:
WebElement element = (new WebDriverWait(getDriver(), 10)).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("input#houseName")));
See ExpectedConditions class Javadoc
for list of all conditions you are able to check.
Imran's answer rehashed for Java 7:
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver wdriver) {
return ((JavascriptExecutor) driver).executeScript(
"return document.readyState"
).equals("complete");
}
});

- 30,738
- 21
- 105
- 131

- 173
- 1
- 6
This seems to be a serious limitation of WebDriver. Obviously waiting for an element will not imply the page being loaded, in particular the DOM can be fully build (onready state) whereby JS is still executing and CSS and images are still loading.
I believe the simplest solution is to set a JS variable upon the onload event after everything is initialized and check and wait for this JS variable in Selenium.

- 6,270
- 7
- 40
- 50
-
1
-
Yep, just use a JavascriptExecutor to execute jQuery.js and then you have access to jQuery load events. It is a rare case when this is necessary though. The standard Webdriver has enough power to do 98% of proper waits. – djangofan Apr 04 '14 at 16:06
-
@djangofan would be awesome to see an example of that... I'm a front-end guy so not sure where or how JavascriptExecutor is used. – BradGreens Apr 29 '14 at 15:24
-
@BradGreens - Ok, look at my project here: https://github.com/djangofan/jquery-growl-selenium-example . If you have the bandwidth to finish that example , I couldn't quite get the jGrowl to work in that test project, although the jQuery works fine. – djangofan Apr 29 '14 at 16:21
-
1@BradGreens In addition to djangofan's comment see my answer here: http://stackoverflow.com/a/24638792/730326 – jmathew Jul 08 '14 at 18:15
Man all these answers require too much code. This should be a simple thing as its pretty common.
Why not just inject some simple Javascript with the webdriver and check. This is the method I use in my webscraper class. The Javascript is pretty basic even if you don't know it.
def js_get_page_state(self):
"""
Javascript for getting document.readyState
:return: Pages state. See doc link below.
"""
ready_state = self.driver.execute_script('return document.readyState')
if ready_state == 'loading':
self.logger.info("Loading Page...")
elif ready_state == 'interactive':
self.logger.info("Page is interactive")
elif ready_state == 'complete':
self.logger.info("The page is fully loaded!")
return ready_state
More Info in "Document.readyState" of MDN Web Docs: https://developer.mozilla.org/en-US/docs/Web/API/Document/readyState

- 575
- 2
- 10
- 26

- 334
- 5
- 9
If you want to wait for a specific element to load, you can use the isDisplayed()
method on a RenderedWebElement
:
// Sleep until the div we want is visible or 5 seconds is over
long end = System.currentTimeMillis() + 5000;
while (System.currentTimeMillis() < end) {
// Browsers which render content (such as Firefox and IE) return "RenderedWebElements"
RenderedWebElement resultsDiv = (RenderedWebElement) driver.findElement(By.className("gac_m"));
// If results have been returned, the results are displayed in a drop down.
if (resultsDiv.isDisplayed()) {
break;
}
}
(Example from The 5 Minute Getting Started Guide)
-
4A year later (current Selenium version 2.23.1), there's no `RenderedWebElement` in the API. However, `isDisplayed()` method is now available directly on `WebElement`. – Petr Janeček Jun 10 '12 at 12:56
-
2
Explicitly wait or conditional wait in this wait until given this condition.
WebDriverWait wait = new WebDriverWait(wb, 60);
wait.until(ExpectedConditions.elementToBeClickable(By.name("value")));
This will wait for every web element for 60 seconds.
Use implicitly wait for wait of every element on page till that given time.
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
This will wait for every web element for 60 seconds.

- 2,555
- 3
- 21
- 29

- 1,303
- 1
- 15
- 21
I'm surprised that predicates weren't the first choice as you typically know what element(s) you will next interact with on the page you're waiting to load. My approach has always been to build out predicates/functions like waitForElementByID(String id)
and waitForElemetVisibleByClass(String className)
, etc. and then use and reuse these wherever I need them, be it for a page load or page content change I'm waiting on.
For example,
In my test class:
driverWait.until(textIsPresent("expectedText");
In my test class parent:
protected Predicate<WebDriver> textIsPresent(String text){
final String t = text;
return new Predicate<WebDriver>(){
public boolean apply(WebDriver driver){
return isTextPresent(t);
}
};
}
protected boolean isTextPresent(String text){
return driver.getPageSource().contains(text);
}
Though this seems like a lot, it takes care of checking repeatedly for you and the interval for how often to check can be set along with the ultimate wait time before timing out. Also, you will reuse such methods.
In this example, the parent class defined and initiated the WebDriver driver
and the WebDriverWait driverWait
.
I hope this helps.

- 30,738
- 21
- 105
- 131

- 141
- 2
- 3
-
This helps me! Thanks for this excellent sample. I add it in my SeleniumHelper; cf. [javabox](https://github.com/boly38/javabox) – boly38 Jun 20 '14 at 09:49
Use implicitly wait for wait of every element on page till given time.
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
this wait for every element on page for 30 sec.
Another wait is Explicitly wait or conditional wait in this wait until given condition.
WebDriverWait wait = new WebDriverWait(driver, 40);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("someid")));
In id give static element id which is diffidently display on the page, as soon as page is load.

- 107
- 1
- 14
The best way to wait for page loads when using the Java bindings for WebDriver is to use the Page Object design pattern with PageFactory. This allows you to utilize the AjaxElementLocatorFactory
which to put it simply acts as a global wait for all of your elements. It has limitations on elements such as drop-boxes or complex javascript transitions but it will drastically reduce the amount of code needed and speed up test times. A good example can be found in this blogpost. Basic understanding of Core Java is assumed.
http://startingwithseleniumwebdriver.blogspot.ro/2015/02/wait-in-page-factory.html

- 961
- 10
- 19
NodeJS Solution:
In Nodejs you can get it via promises...
If you write this code, you can be sure that the page is fully loaded when you get to the then...
driver.get('www.sidanmor.com').then(()=> {
// here the page is fully loaded!!!
// do your stuff...
}).catch(console.log.bind(console));
If you write this code, you will navigate, and selenium will wait 3 seconds...
driver.get('www.sidanmor.com');
driver.sleep(3000);
// you can't be sure that the page is fully loaded!!!
// do your stuff... hope it will be OK...
From Selenium Documentation (Nodejs):
this.get( url ) → Thenable<undefined>
Schedules a command to navigate to the given URL.
Returns a promise that will be resolved when the document has finished loading.
You can use the below existing method to set the pageLoadTimeout
. In below example if the page is taking more than 20 seconds to load, then it will throw an exception of page reload:
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().pageLoadTimeout(20, TimeUnit.SECONDS);

- 806
- 3
- 12
- 20

- 4,623
- 1
- 42
- 50
Call below Function in your script , this will wait till page is not loaded using javascript
public static boolean isloadComplete(WebDriver driver)
{
return ((JavascriptExecutor) driver).executeScript("return document.readyState").equals("loaded")
|| ((JavascriptExecutor) driver).executeScript("return document.readyState").equals("complete");
}

- 16,610
- 15
- 78
- 125
SeleniumWaiter:
import com.google.common.base.Function;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.WebDriverWait;
public class SeleniumWaiter {
private WebDriver driver;
public SeleniumWaiter(WebDriver driver) {
this.driver = driver;
}
public WebElement waitForMe(By locatorname, int timeout){
WebDriverWait wait = new WebDriverWait(driver, timeout);
return wait.until(SeleniumWaiter.presenceOfElementLocated(locatorname));
}
public static Function<WebDriver, WebElement> presenceOfElementLocated(final By locator) {
// TODO Auto-generated method stub
return new Function<WebDriver, WebElement>() {
@Override
public WebElement apply(WebDriver driver) {
return driver.findElement(locator);
}
};
}
}
And to you use it:
_waiter = new SeleniumWaiter(_driver);
try {
_waiter.waitForMe(By.xpath("//..."), 10);
}
catch (Exception e) {
// Error
}

- 30,738
- 21
- 105
- 131

- 215
- 4
- 11
/**
* Call this method before an event that will change the page.
*/
private void beforePageLoad() {
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("document.mpPageReloaded='notYet';");
}
/**
* Call this method after an event that will change the page.
*
* @see #beforePageLoad
*
* Waits for the previous page to disappear.
*/
private void afterPageLoad() throws Exception {
(new WebDriverWait(driver, 10)).until(new Predicate<WebDriver>() {
@Override
public boolean apply(WebDriver driver) {
JavascriptExecutor js = (JavascriptExecutor) driver;
Object obj = js.executeScript("return document.mpPageReloaded;");
if (obj == null) {
return true;
}
String str = (String) obj;
if (!str.equals("notYet")) {
return true;
}
return false;
}
});
}
You can change from the document to an element, in the case of where only part of a document is being changed.
This technique was inspired by the answer from sincebasic.

- 439
- 2
- 8
You can explicitly wait for an element to show up on the webpage before you can take any action (like element.click()
):
driver.get("http://somedomain/url_that_delays_loading");
WebElement myDynamicElement = (new WebDriverWait(driver, 10))
.until(new ExpectedCondition<WebElement>() {
@Override
public WebElement apply(WebDriver d) {
return d.findElement(By.id("myDynamicElement"));
}
}
);
This is what I used for a similar scenario and it works fine.
-
i think driver.get waits for the onload function to finish before return control to the code, unless the page has alot of ajax – goh Apr 20 '12 at 04:44
My simple way:
long timeOut = 5000;
long end = System.currentTimeMillis() + timeOut;
while (System.currentTimeMillis() < end) {
if (String.valueOf(
((JavascriptExecutor) driver)
.executeScript("return document.readyState"))
.equals("complete")) {
break;
}
}

- 3,228
- 5
- 32
- 52
You can use this snippet of code for the page to load:
IWait wait = new OpenQA.Selenium.Support.UI.WebDriverWait(driver,TimeSpan.FromSeconds(30.00));
wait.Until(driver1 => ((IJavaScriptExecutor)driver).ExecuteScript("return document.readyState").Equals("complete"));
Or you can use waiter for any element to be loaded and become visible/clickable on that page, most probably which is going to be load at the end of loading like:
Wait.Until(ExpectedConditions.ElementToBeClickable(By.XPath(xpathOfElement));
var element = GlobalDriver.FindElement(By.XPath(xpathOfElement));
var isSucceededed = element != null;

- 1,176
- 2
- 12
- 29
The best way I've seen is to utilize the stalenessOf
ExpectedCondition, to wait for the old page to become stale.
Example:
WebDriver driver = new FirefoxDriver();
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement oldHtml = driver.findElement(By.tagName("html"));
wait.until(ExpectedConditions.stalenessOf(oldHtml));
It'll wait for ten seconds for the old HTML tag to become stale, and then throw an exception if it doesn't happen.

- 1,339
- 1
- 24
- 29
-
1a WebElement going stale does not imply a new page is done loading. – Corey Goldberg Jan 26 '17 at 17:50
-
Sure, but it means that the old page is finished unloading. In my experience, it's just as important to know when the old page has unloaded, or if it has halted for some reason. – forresthopkinsa Jan 27 '17 at 17:24
-
Of course, I typically use stalenessOf in conjunction with other tests to get the full unload/load process. – forresthopkinsa Jan 27 '17 at 17:25
I use node + selenium-webdriver(which version is 3.5.0 now). what I do for this is:
var webdriver = require('selenium-webdriver'),
driver = new webdriver.Builder().forBrowser('chrome').build();
;
driver.wait(driver.executeScript("return document.readyState").then(state => {
return state === 'complete';
}))

- 65
- 1
- 1
- 10
You can use wait. there are basically 2 types of wait in selenium
- Implicit wait
- Explicit wait
- Implicit wait
This is very simple please see syntax below:
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
- Explicit wait
Explicitly wait or conditional wait in this wait until given condition is occurred.
WebDriverWait wait = new WebDriverWait(driver, 40);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("someid")));
You can use other properties like visblityOf()
, visblityOfElement()

- 4,607
- 2
- 15
- 36
If someone uses selenide:
public static final Long SHORT_WAIT = 5000L; // 5 seconds
$("some_css_selector").waitUntil(Condition.appear, SHORT_WAIT);
More Conditions can be found here: http://selenide.org/javadoc/3.0/com/codeborne/selenide/Condition.html

- 4,998
- 8
- 34
- 54
In my case , I used the following to know the page load status. In our application loading gif(s) are present and, I listen to them as follows to eliminate unwanted wait time in the script.
public static void processing(){
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[@id='Msgpanel']/div/div/img")));
wait.until(ExpectedConditions.invisibilityOfElementLocated(By.xpath("//div[@id='Msgpanel']/div/div/img")));
}
Where the xpath locates the gif in the HTML DOM. After this, You may also implement your action methods Click.
public static void click(WebElement elementToBeClicked){
WebDriverWait wait = new WebDriverWait(driver, 45);
wait.until(ExpectedConditions.visibilityOf(element));
wait.until(ExpectedConditions.elementToBeClickable(element));
wait.ignoring(NoSuchElementException.class).ignoring(StaleElementReferenceException.class); elementToBeClicked.click();
}

- 2,555
- 3
- 21
- 29

- 41
- 4
How to get Selenium to wait for page load after a click provides the following interesting approach:
- Store a reference to a
WebElement
from the old page. - Click the link.
- Keep on invoking operations on the
WebElement
untilStaleElementReferenceException
is thrown.
Sample code:
WebElement link = ...;
link.click();
new WebDriverWait(webDriver, timeout).until((org.openqa.selenium.WebDriver input) ->
{
try
{
link.isDisplayed();
return false;
}
catch (StaleElementReferenceException unused)
{
return true;
}
});

- 30,738
- 21
- 105
- 131

- 86,244
- 97
- 390
- 689
-
Good idea! I never thought to tackle this situation by checking the opposite of a successful page load, a successful page unloading (for lack of a better term). Though whether this is the best option is based on whether StaleElementReferenceException takes less time, etc than waiting for a successful load. Nonetheless, another good way to do it. – Joseph Orlando Jul 01 '15 at 17:35
-
4This is not going to tell you whether the current page is loaded, it's going to tell you whether the last page (specifically one element) is *unloaded*. You will still need to wait for the current page to load. BTW, you can replace your code above with `new WebDriverWait(driver, 10).until(ExpectedConditions.stalenessOf(element))`. – JeffC Aug 19 '16 at 20:32
You can try this code to let the page load completely until element is found.
public void waitForBrowserToLoadCompletely() {
String state = null;
String oldstate = null;
try {
System.out.print("Waiting for browser loading to complete");
int i = 0;
while (i < 5) {
Thread.sleep(1000);
state = ((JavascriptExecutor) driver).executeScript("return document.readyState;").toString();
System.out.print("." + Character.toUpperCase(state.charAt(0)) + ".");
if (state.equals("interactive") || state.equals("loading"))
break;
/*
* If browser in 'complete' state since last X seconds. Return.
*/
if (i == 1 && state.equals("complete")) {
System.out.println();
return;
}
i++;
}
i = 0;
oldstate = null;
Thread.sleep(2000);
/*
* Now wait for state to become complete
*/
while (true) {
state = ((JavascriptExecutor) driver).executeScript("return document.readyState;").toString();
System.out.print("." + state.charAt(0) + ".");
if (state.equals("complete"))
break;
if (state.equals(oldstate))
i++;
else
i = 0;
/*
* If browser state is same (loading/interactive) since last 60
* secs. Refresh the page.
*/
if (i == 15 && state.equals("loading")) {
System.out.println("\nBrowser in " + state + " state since last 60 secs. So refreshing browser.");
driver.navigate().refresh();
System.out.print("Waiting for browser loading to complete");
i = 0;
} else if (i == 6 && state.equals("interactive")) {
System.out.println(
"\nBrowser in " + state + " state since last 30 secs. So starting with execution.");
return;
}
Thread.sleep(4000);
oldstate = state;
}
System.out.println();
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}

- 11
- 1
For Programmers using java 8 onward can use below code to wait for page load using explicit wait.
JavascriptExecutor js = (JavascriptExecutor) driver;
new WebDriverWait(driver, 10).until(webDriver ->
(js).executeScript("return document.readyState;").equals("complete"));
Note: In my above code Lambda Expression is used, which is only available in java 8 onward version.
For Programmers using lower version of Java i.e. below Java 8 can use:
ExpectedCondition<Boolean> cond = new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver input) {
JavascriptExecutor js = (JavascriptExecutor) driver;
return js.executeScript("return document.readyState;").equals("complete");
}
};
new WebDriverWait(driver, 100).until(cond);

- 51
- 5
driver.asserts().assertElementFound("Page was not loaded",
By.xpath("//div[@id='actionsContainer']"),Constants.LOOKUP_TIMEOUT);

- 3,587
- 30
- 27
The easiest way is just wait for some element which will appear on loaded page.
If you would like to click on some button already after page is loaded you could use await and click:
await().until().at.most(20, TimeUnit.Seconds).some_element.isDisplayed(); // or another condition
getDriver().find(some_element).click;
WebDriver driver = new ff / chrome / anyDriverYouWish(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
Waits maximum of 10 Seconds.WebDriverWait wait = new WebDriverWait(driver, 10); wait.until(ExpectedConditions.visibilityOf(WebElement element));
FluentWait<Driver> fluentWait; fluentWait = new FluentWait<>(driver).withTimeout(30, TimeUnit.SECONDS) .pollingEvery(200, TimeUnit.MILLISECONDS) .ignoring(NoSuchElementException.class);
The advantage of the last option is that you can include exception to be expected, so that your execution continues.

- 28,498
- 28
- 50
- 59

- 121
- 1
- 7
use a if condition and for any of the element present
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

- 132,869
- 46
- 340
- 423

- 39
- 4
For implicit wait you can use something like following:
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS)
In order for webpage to wait for a specific object to be visible or cerntain condition to be true. You can use wait feather of web driver.
//120 is maximum number of seconds to wait.
WebDriverWait wait = new WebDriverWait(driver,120);
wait.until(ExpectedConditions.elementToBeClickable("CONDITITON"));
In Java, another option is to sleep the thread for specific time.
Thread.sleep(numberOfSeconds*1000);
//This line will cause thread to sleep for seconds as variable
I created a method to simplify thread.sleep method
public static void wait_time(int seconds){
try {
Thread.sleep(seconds*1000);
}catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Use the method as wait_time(10); The thread will sleep for 10 seconds.

- 2,555
- 3
- 21
- 29

- 59
- 1
- 14
private static void checkPageIsReady(WebDriver driver) {
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;
}
}
}

- 2,555
- 3
- 21
- 29

- 1,665
- 1
- 22
- 32
use following code it's very easy and simple for page load.
public void PageLoad(IWebDriver driver, By by)
{
try
{
Console.WriteLine("PageLoad" + by);
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(30));
wait.Until(ExpectedConditions.ElementIsVisible(by));
wait = new WebDriverWait(driver, TimeSpan.FromSeconds(30)); // 30 seconds wait until element not found.
wait.Until(ExpectedConditions.ElementToBeClickable(by));
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Assert.Fail("Element not found!")
}
}
i hope this helps you.

- 2,555
- 3
- 21
- 29

- 13
- 10
public static int counter = 0;
public void stepGeneralWait() {
boolean breakIt = true;
while (true) {
breakIt = true;
try {
do{
// here put e.g. your spinner ID
Controller.driver.findElement(By.xpath("//*[@id='static']/div[8]/img")).click();
Thread.sleep(10000);
counter++;
if (counter > 3){
breakIt = false;
}
}
while (breakIt);
} catch (Exception e) {
if (e.getMessage().contains("element is not attached")) {
breakIt = false;
}
}
if (breakIt) {
break;
}
}
try {
Thread.sleep(12000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

- 5,093
- 12
- 35
- 44

- 21
- 4
Use this function
public void waitForPageLoad(ChromeDriver d){
String s="";
while(!s.equals("complete")){
s=(String) d.executeScript("return document.readyState");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

- 385
- 4
- 5
-
webdriver already does essentially the same thing internally. this function is just redundant. – Corey Goldberg Jan 26 '17 at 17:52
Use:
driver.manage().timeOuts().implicitlyWait(10, TimeUnit.SECONDS);
Which means any search for the elements on the web page could take time to load. The implicitlyWait
is set before throwing an exception.
The TimeUnit
displays whichever way you want to wait in (seconds, minutes, hours and days).

- 30,738
- 21
- 105
- 131
There are 2 types of waits available in Webdriver/Selenium 2 software testing tool. One of them is Implicit wait and another one is explicit wait. Both (Implicit wait and explicit wait) are useful for waiting in WebDriver. Using waits, we are telling WebDriver to wait for a certain amount of time before going to next step.You can use implicit wait for page load waiting.
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

- 5,965
- 14
- 31
- 57

- 1
- 3
I don't think an implicit wait is what you want. Try this:
driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
More information in the documentation

- 33
- 4
This code will wait until all the elements on the page are loaded in the DOM.
WebDriver driver = new WebDriver();
WebDriverWait wait = new WebDriverWait(driver, timeout);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*")));

- 1
- 1
-
Many elements on pages will never be visible which means this will time out every time. – JeffC May 18 '18 at 18:53
Implicit and explicit wait is better.
But if you are handling an exception in Java, then you can use this for waiting for a page to reload:
Thead.sleep(1000);

- 30,738
- 21
- 105
- 131

- 2,516
- 1
- 13
- 8