【问题标题】:How to extend IWebElement interface to add a new method如何扩展 IWebElement 接口以添加新方法
【发布时间】:2023-03-18 02:45:01
【问题描述】:

我正在尝试在 C# 中扩展接口 IWebElement 以添加一种新方法来防止 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可以一直使用它?

谢谢你, 问候。

【问题讨论】:

    标签: c# selenium interface extends staleelementreferenceexception


    【解决方案1】:

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

    创建一个新的static class ExtensionMethods:


    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# Programing guide for Extension Methods

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-25
      • 1970-01-01
      相关资源
      最近更新 更多