最好的办法是通过使用名为“等待”的内置Selenium功能。我使用此代码6个月以上,没有任何问题。
第1步:创建扩展方法。
private static WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(20));
public static void WaitUntilAttributeValueEquals(this IWebElement webElement, String attributeName, String attributeValue)
{
wait.Until<IWebElement>((d) =>
{
//var x = webElement.GetAttribute(attributeName); //for debugging only
if (webElement.GetAttribute(attributeName) == attributeValue)
{
return webElement;
}
return null;
});
}
步骤2:使用
IWebElement x = driver.FindElement(By.ClassName("myInput")) // Initialization
x.WaitUntilAttributeValueEquals("readonly",null)
input.SendKeys("Text");
说明:该代码将检查每500ms(这是 '等待' 方法的默认行为)中20秒,是否 “readonly
” 属性指定的IWebElement
等于null。如果在20秒后,它仍然不是null
,抛出异常。当值更改为null
时,您的下一行代码将被执行。
在使用Selenium时最好使用WebDriverWait。 –