Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selenium -- How to wait until page is completely loaded [duplicate]

I am trying to automate some test cases using Java and Selenium WebDriver. I have the following scenario:

  • There is a page named 'Products'. When I click on 'View Details' link in the 'Product' page, a popup (modal-dialog) containing the details of the item appears.
  • When I click on the 'Close' button in the popup the popup closes and the page automatically refreshes (the page is just reloading, the contents remain unchanged).
  • After closing the popup I need to click on 'Add Item' button in the same page. But when WebDriver trying to find the 'Add Item' button, if the internet speed is too fast, WebDriver can find and click the element.

  • But if the internet is slow, WebDriver finds the button before the page refresh, but as soon as the WebDriver click on the button, the page refreshes and StaleElementReferenceException occurs.

  • Even if different waits are used, all the wait conditions become true (since the contents in the page are same before and after reload) even before the page is reloaded and StaleElementReferenceException occurs.

The test case works fine if Thread.sleep(3000); is used before clicking on the 'Add Item' button. Is there any other workaround for this problem?

like image 801
stackoverflow Avatar asked Apr 13 '16 06:04

stackoverflow


People also ask

How will you wait until a Web page has been loaded completely?

We can wait until the page is completely loaded in Selenium webdriver by using the JavaScript Executor. Selenium can run JavaScript commands with the help of the executeScript method. We have to pass return document.

Which wait statement will be used to wait till page load?

Explicit Wait The explicit wait is used to tell the Web Driver to wait for certain conditions (Expected Conditions) or the maximum time exceeded before throwing an "ElementNotVisibleException" exception.


1 Answers

3 answers, which you can combine:

  1. Set implicit wait immediately after creating the web driver instance:

    _ = driver.Manage().Timeouts().ImplicitWait;

    This will try to wait until the page is fully loaded on every page navigation or page reload.

  2. After page navigation, call JavaScript return document.readyState until "complete" is returned. The web driver instance can serve as JavaScript executor. Sample code:

    C#

    new WebDriverWait(driver, MyDefaultTimeout).Until( d => ((IJavaScriptExecutor) d).ExecuteScript("return document.readyState").Equals("complete")); 

    Java

    new WebDriverWait(firefoxDriver, pageLoadTimeout).until(       webDriver -> ((JavascriptExecutor) webDriver).executeScript("return document.readyState").equals("complete")); 
  3. Check if the URL matches the pattern you expect.

like image 194
Kim Homann Avatar answered Oct 22 '22 06:10

Kim Homann