我试图在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,并且许多元素都是dinamycally创建/销毁,因此为每个WebElement添加保护成为一个巨大的考验。
所以问题就变成了:我应该如何实现这个方法,以便IWebElement接口可以随时使用它?
谢谢,问候。
对于任何达到此问题的人都有相同的问题,以下是我修复它的方法:
创建一个新的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
希望这可以帮助