How I can check whether a page is loaded completely or not in web driver?

前端 未结 9 1839
走了就别回头了
走了就别回头了 2020-12-01 01:33

I am writing some Java Webdriver code to automate my application. How can I correctly check whether the page has been loaded or not? The application has some Ajax calls, too

9条回答
  •  死守一世寂寞
    2020-12-01 02:04

    I know this post is old. But after gathering all code from above I made a nice method (solution) to handle ajax running and regular pages. The code is made for C# only (since Selenium is definitely a best fit for C# Visual Studio after a year of messing around).

    The method is used as an extension method, which means to put it simple; that you can add more functionality (methods) in this case, to the object IWebDriver. Important is that you have to define: 'this' in the parameters to make use of it.

    The timeout variable is the amount of seconds for the webdriver to wait, if the page is not responding. Using 'Selenium' and 'Selenium.Support.UI' namespaces it is possible to execute a piece of javascript that returns a boolean, whether the document is ready (complete) and if jQuery is loaded. If the page does not have jQuery then the method will throw an exception. This exception is 'catched' by error handling. In the catch state the document will only be checked for it's ready state, without checking for jQuery.

    public static void WaitUntilDocumentIsReady(this IWebDriver driver, int timeoutInSeconds) {
        var javaScriptExecutor = driver as IJavaScriptExecutor;
        var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(timeoutInSeconds));
    
        try {
            Func readyCondition = webDriver => (bool)javaScriptExecutor.ExecuteScript("return (document.readyState == 'complete' && jQuery.active == 0)");
            wait.Until(readyCondition);
        } catch(InvalidOperationException) {
            wait.Until(wd => javaScriptExecutor.ExecuteScript("return document.readyState").ToString() == "complete");
        }
    }
    

提交回复
热议问题