2013-08-30 34 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)); 
}