C#Selenium:没有轮询间隔会导致条件失败

时间:2018-05-23 17:12:31

标签: c# selenium-webdriver

我使用自定义条件点击按钮,直到它按照以下方式消失:

public bool UntilGone(By targetLocator)
    {
        Waits.Default.Until(ExpectedConditions.ElementToBeClickable(targetLocator));

        return Waits.Default.Until(d =>
        {
            try
            {
                _Action.Invoke(d.FindElement(targetLocator));
            }
            catch (StaleElementReferenceException) { }
            catch (NoSuchElementException) { }

            Thread.Sleep(200); // this one here

            return ExpectedConditions.InvisibilityOfElementLocated(targetLocator).Invoke(d);

        });
    }

出于某种原因,在我添加Thread.Sleep(200)之前,它失败了一个条件并引发了超时异常。

为什么?单击后该元素仍然消失,它仍然尝试单击它,捕获所有异常,完成隐身条件并正确退出等待。但它并没有。超时异常表明,当元素明显消失时,它会将其视为可见元素。我在这里错过了什么?为什么Thread.Sleep会有所作为?

1 个答案:

答案 0 :(得分:0)

您发布的方法并未实际点击该元素。它只是等待它可点击。我不确定为什么睡眠会影响任何事情。

我会以不同的方式编写该函数。我还建议你给它一个更具描述性的名字,我选择ClickAndWaitUntilInvisible()。下面的方法等待元素可点击,单击它,然后等待元素不可见。如果成功则返回true,否则返回false

public bool ClickAndWaitUntilInvisible(By targetLocator)
{
    try
    {
        Waits.Default.Until(ExpectedConditions.ElementToBeClickable(targetLocator)).Click();
        return Waits.Default.Until(ExpectedConditions.InvisibilityOfElementLocated(targetLocator));
    }
    catch (TimeoutException)
    {
        return false;
    }
}