2013-08-30 30 views
1

入门org.openqa.selenium.StaleElementReferenceException:元素不再附加到DOM获取StaleElementReferenceException执行checkbox.click后()

list = driver.findElements(By.cssSelector(listLocator)); 
for (WebElement listItem : list) { 

checkbox = listItem.findElement(By.cssSelector(checkboxLocator)); 
checkbox.click(); 

String path = checkbox.getCssValue("background-image")); 
} 

执行checkbox.click();后我不能调用任何方法checkbox元素

相应的图像: enter image description here

我定位器

peforming checkbox.click()前10
listLocator = ul[class="planList"] > li[class="conditionsTextWrapper"] 
checkboxLocator = label[role="button"] > span[class="ui-button-text"] 

我的HTML源:

<ul class="planList">  
<li class="conditionsTextWrapper" > 
    <input name="chkSubOpt" type="checkbox"> 
    <label class="check ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" for="CAT_5844" aria-pressed="false" role="button"> 
    <span class="ui-button-text"></span> 
    </label> 
    <label class="conditionsText">Eat at least 5 fruits and vegetables every day</label> 
</li> 
</ul> 

执行checkbox.click()后:

<ul class="planList">  
    <li class="conditionsTextWrapper" > 
    <input name="chkSubOpt" type="checkbox"> 
    <label class="check ui-button ui-widget ui-state-default ui-corner-all ui-state-active ui-button-text-only" for="CAT_5844" aria-pressed="true" role="button" aria-disabled="false"> 
    <label class="conditionsText">Eat at least 5 fruits and vegetables every day</label> 
    </li> 
</ul> 

回答

0

你的DOM是变化继.click(),作为这样的参考Webdriver形成为涉及该元素(如列表中的下一个)不再有效。因此,您将需要在循环中重建列表。

list = driver.findElements(By.cssSelector(listLocator)); 
for (i=0; list.length(); i++) { 
    list = driver.findElements(By.cssSelector(listLocator)); 
    checkbox = list[i].findElement(By.cssSelector(checkboxLocator)); 
    checkbox.click(); 

    String path = checkbox.getCssValue("background-image")); 
} 
0

这会发生,因为您的DOM结构已经改变,因为您已经引用了您的复选框。

这是人们得到的一个非常常见的异常。

WorkAround可以捕捉异常并尝试定位并再次单击相同的元素。

WebElement date = driver.findElement(By.linkText("date")); 
date.click(); 
         } 
         catch(org.openqa.selenium.StaleElementReferenceException ex) 
         { 
          log.debug("Exception in finding date"); 
          log.debug(e); 
          WebElement date = driver.findElement(By.linkText("date")); 
                 date.click(); 
         } 

这可以解决大部分的您的烦恼!

同样适用于您的复选框问题。不过,我建议你使用@Mark Rowlands解决方案。他的代码更干净。

1

如上所述,这些错误的原因是在点击复选框后DOM结构已被更改。以下代码适用于我。

string checkboxXPath = "//input[contains(@id, 'chblRqstState')]"; 
var allCheckboxes = driver.FindElements(By.XPath(checkboxXPath)); 

for (int i = 0; i != allCheckboxes.Count; i++) 
{ 
    allCheckboxes[i].Click(); 
    System.Threading.Thread.Sleep(2000); 
    allCheckboxes = driver.FindElements(By.XPath(checkboxXPath)); 
}