Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
465 views
in Technique[技术] by (71.8m points)

c# - Random errors using wait for element clickable method in Selenium

I have a custom wait method defined as:

public IWebElement WaitForElementClickable(IWebDriver _driver, By elementName)
{
    var wait = new WebDriverWait(_driver, TimeSpan.FromSeconds(20));
    return wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementToBeClickable(elementName))    

}

I have one place where I click on a button and a new page loads, it sticks on "loading" for a few seconds (2-3 secs) and then I want to click on something else once it loads....

        public void enterSearchInfo()
        {

            //Thread.Sleep(2000);
            IWebElement selectElement = utility.WaitForElementClickable(_driver, element);
            selectElement.Click();
        }

Even though I have the wait method set to 20 secs this only works 5 times out of 10, the other 5 times I get the following error...

OpenQA.Selenium.ElementClickInterceptedException: element click intercepted:

When I uncomment Thread.Sleep(2000) it works 10 out of 10 times

Is there a better way to handle this than the wait for element clickable method? I'd rather not be hardcoding sleep waits in my code.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is what I use in a framework I've created. It eats ElementClickInterceptedException and StaleElementReferenceException and keeps trying until the timeout or success. It got rid of a lot of issues like what you are talking about. There are other ways to do it specific to each page but I found that this works really well in a large number of scenarios.

/// <summary>
/// Clicks on an element
/// </summary>
/// <param name="locator">The locator used to find the element.</param>
/// <param name="timeOut">[Optional] How long to wait for the element (in seconds). The default timeOut is 10s.</param>
public void Click(By locator, int timeOut = 10)
{
    DateTime now = DateTime.Now;
    while (DateTime.Now < now.AddSeconds(timeOut))
    {
        try
        {
            new WebDriverWait(Driver, TimeSpan.FromSeconds(timeOut)).Until(ExpectedConditions.ElementToBeClickable(locator)).Click();

            return;
        }

        catch (ElementClickInterceptedException)
        {
            // do nothing, loop again
        }
        catch (StaleElementReferenceException)
        {
            // do nothing, loop again
        }
    }

    throw new Exception($"Unable to click element <{locator}> within {timeOut}s.");
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...