2017-06-19 60 views
1

加載頁面時,我的輸入具有「只讀」屬性。如何檢查該屬性是否已被刪除?我使用的硒與C#等到輸入只讀屬性消失

我的代碼:

IWebElement input = driver.FindElement(By.ClassName("myInput")); 
string inputReadOnly = input.GetAttribute("readonly"); 

while (inputReadOnly == "true") 
     { 
      inputReadOnly = input.GetAttribute("readonly"); 
     } 
input.SendKeys("Text"); 

此代碼的工作,但我認爲有這樣做更合適的方式。

回答

1

我沒有看到任何其他方式使這段代碼比擺脫inputReadOnly變量更好。 如果你不使用它,其他任何地方,你可以用這個代替您while循環:

while (input.GetAttribute("readonly") == "true") 
{ 
    // maybe do a thread.sleep(n_milliseconds); 
} 

希望這有助於。

0

你可以做這樣的事情

IWebElement input = driver.FindElement(By.ClassName("myInput")); 
while (input.GetAttribute("readonly") == "true"); 
input.SendKeys("Text"); 

減少線路的數量可能還需要限制要等待這個時間,以避免無限循環

IWebElement input = driver.FindElement(By.ClassName("myInput")); 

Stopwatch stopwatch = new Stopwatch(); 
stopwatch.Start(); 

while (input.GetAttribute("readonly") == "true" && stopwatch.Elapsed.TotalSeconds < timeoutInSeconds); 

input.SendKeys("Text"); 
+0

在使用Selenium時最好使用WebDriverWait。 –

1

最好的辦法是通過使用名爲「等待」的內置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時,您的下一行代碼將被執行。

+0

你能分享一下你的意思嗎?據我所知,ExpectedConditions不包含'AttributeToBe'的定義。 –