2017-06-19 59 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'的定义。 –