【问题标题】:C# - Selenium - How to wait until page is fully loadedC# - Selenium - 如何等到页面完全加载
【发布时间】:2018-03-09 10:59:30
【问题描述】:

由于我的测试网站同步缓慢,我需要等待页面完全加载。我已经尝试了几个元素等待:

WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(50));
wait.Until(ExpectedConditions.ElementExists(By.XPath("//input[@placeholder='First Name']"))).SendKeys("FirstName");

我也尝试过使用 JavaScript 方法,例如:

public static void WaitForLoadOriginal(IWebDriver driver)
{
    IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
    int timeoutSec = 15;
    WebDriverWait wait = new WebDriverWait(driver, new TimeSpan(0, 0, timeoutSec));
    wait.Until(wd => js.ExecuteScript("return document.readyState").ToString() == "complete");
}

这是我尝试选择的代码

<select name="question" id="question1" type="text" class="form-control ng-pristine ng-empty ng-invalid ng-invalid-required ng-touched" ng-required="true" 

这是我得到的例外:

WebDriver.Support.dll 中出现“OpenQA.Selenium.NoSuchElementException”类型的异常,但未在用户代码中处理 $exception {"Cannot locate option with index: 1"} OpenQA.Selenium.NoSuchElementException

如果我输入Thread.Sleep(20000),它就可以正常工作。但我不想使用静态等待。要么我没有正确使用上述方法,要么它们不起作用。任何帮助将不胜感激。

【问题讨论】:

  • 您的 HTML &lt;select name="question" id="question1" type="text" class="form-control...代码尝试 By.XPath("//input[@placeholder='First Name']") 不匹配。
  • IWebElement SecurityQuestion1 = wait.Until(ExpectedConditions.ElementToBeClickable(By.Id("question1"))); SelectElement DropDownSecurityQuestion1 = new SelectElement(SecurityQuestion1); DropDownSecurityQuestion1.SelectByIndex(1);

标签: c# selenium selenium-webdriver pageload webdriverwait


【解决方案1】:

根据您的代码块,您尝试沿 WebDriverWait 调用 SendKeys() 而不是 ExpectedConditions 子句作为 ElementExists 你应该使用子句ElementToBeClickable 如下:

WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(20));
wait.Until(ExpectedConditions.ElementToBeClickable(By.XPath("//input[@placeholder='First Name']"))).SendKeys("FirstName");

【讨论】:

  • 我试过了。无法解决问题。仍然失败。
  • could not solveStill fails 并没有说明发生了什么错误。使用相关的 HTMLcode trialerror stack trace 更新问题。由于Thread.Sleep(20000) 为您工作,请尝试将时间跨度增加到 20 秒
【解决方案2】:

要执行等待页面加载,这段代码对我来说很好。

protected void WaitForPageLoad()
    {
        wait.Until(driver=>((IJavaScriptExecutor)driver).ExecuteScript("return document.readyState").Equals("complete"));
    }

谢谢

【讨论】:

    猜你喜欢
    • 2016-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多