简体   繁体   中英

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. However it is not as straightforward as it may seem. I'm working around with Thread.Sleep(3000); but I'm sure there should be a better solution. So, my code works as follows:

  1. Load page with firefox driver.
  2. Execute a javascript snnipet to change language (I need to wait for this in order to login).

     IJavaScriptExecutor executor = (IJavaScriptExecutor)firefox; executor.ExecuteScript("arguments[0].click();", idioma_español); 
  3. Above instruction leads to a page reload.

  4. 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)); 
  5. Continue to login.

However, when I run the code, it throws the following exception:

在此处输入图片说明

Looking closer into de output, I found this:

在此处输入图片说明

在此处输入图片说明

I tried with different expected conditions such as: TextToBePresentInElement , ElementExists ; but it throws the same exception.

I also tried with 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. 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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM