[英]Exception: “Timed Out After xx seconds” on wait.until Selenium WebDriver C#
I'm trying to figure out how it's possible to wait for a condition in order to login into a web page with Selenium Driver. 我试图弄清楚如何等待条件以便使用Selenium Driver登录到网页。 However it is not as straightforward as it may seem. 但是,它并不像看起来那样简单。 I'm working around with Thread.Sleep(3000);
我正在研究Thread.Sleep(3000);
but I'm sure there should be a better solution. 但我相信应该有更好的解决方案。 So, my code works as follows: 因此,我的代码如下:
Execute a javascript snnipet to change language (I need to wait for this in order to login). 执行一个javascript代码片段以更改语言(我需要等待此时间才能登录)。
IJavaScriptExecutor executor = (IJavaScriptExecutor)firefox; executor.ExecuteScript("arguments[0].click();", idioma_español);
Above instruction leads to a page reload. 以上说明导致页面重新加载。
Next instruction is intented to wait for page to be reloaded 下一条指令旨在等待页面重新加载
WebDriverWait wait = new WebDriverWait(newDriver,TimeSpan.FromSeconds(10)); wait.Until(ExpectedConditions.TextToBePresentInElementValue(element,textToAppear));
Continue to login. 继续登录。
However, when I run the code, it throws the following exception: 但是,当我运行代码时,它将引发以下异常:
Looking closer into de output, I found this: 仔细查看de输出,我发现了这一点:
I tried with different expected conditions such as: TextToBePresentInElement
, ElementExists
; 我试着用不同的预期条件,如: TextToBePresentInElement
, ElementExists
; but it throws the same exception. 但会引发相同的异常。
I also tried with ExecuteAsyncScript("arguments[0].click();", idioma_español);
我还尝试了ExecuteAsyncScript("arguments[0].click();", idioma_español);
method, but it throws "Document was unloaded " exception. 方法,但会引发“文档已卸载”异常。
It looks like the text element has been replaced, so the element was stale. 看起来text元素已被替换,因此该元素已过时。 I think you can solve it by fetch the new element every time. 我认为您可以通过每次获取新元素来解决它。 See code below: 参见下面的代码:
public bool WaitForTextToAppear(IWebDriver driver, By elementLocator, string textToAppear, int timeoutInSec=10)
{
IWait<IWebDriver> wait = new DefaultWait<IWebDriver>(driver);
wait.Timeout = TimeSpan.FromSeconds(timeoutInSec);
wait.PollingInterval = TimeSpan.FromMilliseconds(300);
try
{
wait.Until(d => IsTextPresentedIn(d, elementLocator, textToAppear));
return true;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("Error: " + ex.Message);
return false;
}
}
private bool IsTextPresentedIn(IWebDriver driver, By elementLocator, string textToAppear)
{
try
{
var elements = driver.FindElements(elementLocator);
if (elements.Count>0 && elements[0].Text.Equals(textToAppear, StringComparison.OrdinalIgnoreCase))
return true;
}
catch
{
return false;
}
return false;
}
// using the web driver extension.
bool textAppeared = WaitForTextToAppear(driver, By.CssSelector("selector-of-the-text-element"), "HERE IS THE EXPECTED TEXT");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.