How to get webDriver to wait for page to load (C# Selenium project)

后端 未结 7 1267
北荒
北荒 2020-12-04 22:57

I\'ve started a Selenium project in C#. Trying to wait for page to finish loading up and only afterwards proceed to next action.

My code looks like this:

<         


        
7条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-04 23:21

    Just had the same problem. With the folowing Method I wait for the page to load fully, not relying on causing the page load by JavaScript, a click or an action on an input element.

    private void WaitForPageToLoad(Action doing)
    {
        IWebElement oldPage = _driver.FindElement(By.TagName("html"));
        doing();
        WebDriverWait wait = new WebDriverWait(_driver, new TimeSpan(0, 0, Timeout));
        try
        {
            wait.Until(driver => ExpectedConditions.StalenessOf(oldPage)(_driver) &&
                ((IJavaScriptExecutor)driver).ExecuteScript("return document.readyState").Equals("complete"));
        }
        catch (Exception pageLoadWaitError)
        {
            throw new TimeoutException("Timeout during page load", pageLoadWaitError);
        }
    }
    

    called like following

    WaitForPageToLoad(() => _driver.FindElement(By.Id("button1")).Click());
    

提交回复
热议问题