最好的辦法是通過使用名爲「等待」的內置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。 –