首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Selenium中使用等待元素单击方法的随机错误

Selenium中使用等待元素单击方法的随机错误
EN

Stack Overflow用户
提问于 2021-03-26 16:04:59
回答 1查看 368关注 0票数 0

我有一个自定义等待方法,定义为:

代码语言:javascript
复制
public IWebElement WaitForElementClickable(IWebDriver _driver, By elementName)
{
    var wait = new WebDriverWait(_driver, TimeSpan.FromSeconds(20));
    return wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementToBeClickable(elementName))    

}

我有一个地方,我点击一个按钮和一个新的页面加载,它坚持几秒钟“加载”(2-3秒),然后我想点击其他东西,一旦它加载.

代码语言:javascript
复制
        public void enterSearchInfo()
        {

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

即使我将等待方法设置为20秒

代码语言:javascript
复制
OpenQA.Selenium.ElementClickInterceptedException: element click intercepted:

当我取消评论Thread.Sleep(2000)时,它会工作10 / 10次

有比wait for element clickable方法更好的方法来处理这个问题吗?我不想在代码中硬编码睡眠等待。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-03-26 16:25:24

这是我在我创建的框架中使用的。它吃掉ElementClickInterceptedExceptionStaleElementReferenceException,并一直尝试直到超时或成功。它解决了很多问题,比如你在说什么。对于每个页面,有其他方法可以实现它,但是我发现在很多情况下,这种方法非常有效。

代码语言:javascript
复制
/// <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.");
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66820416

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档