【问题标题】:Compound classes stored in an array are not accessible in selenium java在 selenium java 中无法访问存储在数组中的复合类
【发布时间】:2015-06-08 05:48:21
【问题描述】:

单击按钮后我的问题是它显示了一些 6 个选项,我需要存储这些选项的复合类名称,因为我需要单击每个选项。但是当我尝试将类名称存储在数组并开始迭代它成功点击第一个选项但是当尝试点击第二个选项时它给出了异常 “org.openqa.selenium.StaleElementReferenceException:元素不再附加到 DOM”。我在哪里做错了。

这是迭代存储在数组中的类的代码:

List<WebElement> elementsList = new ArrayList<WebElement>(); 
elementsList = ArrayList<WebElement>)driver.findElements((By.cssSelector(".simpleButtonWidget")‌​)); 
Iterator itr = elementsList.listIterator(); 
while(itr.hasNext()) { 
    WebElement tempElement = (WebElement)itr.next(); 
    tempElement =(WebElement)itr.next(); 
    tempElement.click(); 
}

页面代码:

<div class="toolsMenuWidget"> 
<div id="toolsMenuJPlayer" class="jp-jplayer" style="width: 0px; height: 0px;"></div> 
<div class="simpleButtonWidget ConnectingCubesBtn choice_1 up" style="cursor: pointer;" title="Connecting Cubes"></div> 
<div class="simpleButtonWidget NumberCardsBtn choice_2 up" style="cursor: pointer;" title="Number Cards"></div> 
<div class="simpleButtonWidget PlayMoneyBtn up choice_3" style="cursor: pointer;" title="Play Money"></div> 
<div class="simpleButtonWidget PosterBtn up choice_4" style="cursor: pointer;" title="100 Poster"></div> 
</div> 

【问题讨论】:

  • 分享您在数组中存储方式的代码,并分享这 6 个选项的 html 代码。
  • 这是迭代存储在数组中的类的代码: List elementsList = new ArrayList(); elementsList = ArrayList)driver.findElements((By.cssSelector(".simpleButtonWidget")));迭代器 itr = elementsList.listIterator(); while(itr.hasNext()) { WebElement tempElement = (WebElement)itr.next(); tempElement =(WebElement)itr.next(); tempElement.click(); }
  • 似乎当您单击第一个选项时,会发生一些 DOM (html) 更改,因此状态会发生更改。当它发生时,Selenium 会抛出 StaleElelmentReferenceException。所以,你可能需要回到之前的网页状态,然后点击第二个和第三个元素。
  • 当你检查 elementsList.size() 时你得到 6 吗?

标签: java eclipse selenium


【解决方案1】:

您的 while 循环的第二行肯定是错误的:

while(itr.hasNext()) { 
    WebElement tempElement = (WebElement)itr.next(); 
    tempElement =(WebElement)itr.next(); //remove this
    tempElement.click(); 
}

但正如 Vikas Neha Ojha 指出的那样,如果在您单击第一个元素后 DOM 发生变化,则可能会引发 StaleElelmentReferenceException。在这种情况下,您需要再次查找每个元素。鉴于元素的标题是稳定的,这应该可以工作:

String[] titles = { "Connecting Cubes", "Number Cards", "Play Money", "100 Poster" };
for (String title : titles) {
    WebElement element = driver.findElement(By.xpath("//div[@title='" + title + "']"));
    element.click();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多