1

我正在尝试扩展IWebElementC# 中的接口以添加一种新方法来防止StaleElementReferenceException.

我要添加的方法很简单retryingClick,它将尝试在放弃之前最多单击 WebElement 三次:

public static void retryingClick(this IWebElement element)
    {
        int attempts = 0;

        while (attempts <= 2)
        {
            try
            {
                element.Click();
            }
            catch (StaleElementReferenceException)
            {
                attempts++;
            }
        }
    }

添加该方法的原因是我们的网页大量使用了jQuery,并且很多元素是动态创建/销毁的,因此为每个元素添加保护WebElement成为一项巨大的考验。

所以问题就变成了:我应该如何实现这个方法,以便接口IWebElement可以随时使用它?

谢谢,问候。

4

1 回答 1

0

对于遇到相同问题的任何人,这是我修复它的方法:

创建一个新的static classExtensionMethods:


public static class ExtensionMethods
{

    public static bool RetryingClick(this IWebElement element)
    {
        Stopwatch crono = Stopwatch.StartNew();

        while (crono.Elapsed < TimeSpan.FromSeconds(60))
        {
            try
            {
                element.Click();
                return true;
            }
            catch (ElementNotVisibleException)
            {
                Logger.LogMessage("El elemento no es visible. Reintentando...");
            }
            catch (StaleElementReferenceException)
            {
                Logger.LogMessage("El elemento ha desaparecido del DOM. Finalizando ejecución");
            }

            Thread.Sleep(250);
        }

        throw new WebDriverTimeoutException("El elemento no ha sido clicado en el tiempo límite. Finalizando ejecución");
    }
}

这应该足以使该方法RetryingClick显示为 IWebElement 类型的方法

如果您有任何疑问,请查看Microsoft C# 编程指南以了解扩展方法

希望这可以帮助

于 2019-04-08T09:16:35.237 回答