我有一种情况,我试图遍历条形图上的许多元素,直到找到“ rect”标记名。当我单击“ rect”标签名称时,将从图表中选择单个条,然后将我重定向到另一页。请参阅以下有关我正在使用的条形图的图像:
http://imgur.com/xU63X1Z

作为参考,我正在使用的条形图在右上方。我要执行的测试是单击图表中的第一条;这样做会将我重定向到适当的页面。为此,我已使用Eclipse(Java)在Selenium Webdriver中编写了以下代码:

WebElement deliveredChartDailyFocus = driver.findElement(By.id("delivered-chart-daily"));
deliveredChartDailyFocus.click();

List<WebElement> children = deliveredChartDailyFocus.findElements(By.tagName("rect"));
Iterator<WebElement> iter = children.iterator();

while (iter.hasNext()) {
WebElement we = iter.next();

if(we.isDisplayed()){
we.click();
}


上面的代码点击了“ rect”元素并将我重定向到相应的页面,因此一切似乎都正常运行。但是,当我点击该页面时,我得到一个错误,因为代码仍在寻找新页面上没有的“ rect”值。

您会注意到上面缺少一个“中断”行…..这是因为,在调试代码时,我发现在迭代循环时,直到第三次迭代时,click事件才开始生效, m假设因为“ rect”元素不可见?因此,如果我输入“ break”语句,则它会在第一次迭代后退出循环,因此,我永远都不会进入执行“ click”事件的位置来导航到新页面。

从本质上讲,我所追求的是一种能够根据需要循环多次直到找到合适的“ rect”元素的方式。单击后,我将重定向到新页面…。仅在那时,我要退出循环,以便不显示“ NoSuchElementException错误”。

如果需要更多详细信息,请告诉我,非常感谢您对此提供任何指导。

最佳答案

一旦进入新页面,所有这些rect元素都将消失。对这些rect元素进行任何引用都会触发该StaleElementReferenceException

因此,单击后不要引用这些元素。迭代到第一个显示的rect元素,然后停止迭代。

WebElement deliveredChartDailyFocus = driver.findElement(By.id("delivered-chart-daily"));
deliveredChartDailyFocus.click();

// Get a list of all the <rect> elements under the #delivered-chart-daily element
List<WebElement> children = deliveredChartDailyFocus.findElements(By.tagName("rect"));

WebElement elementToClick = null; // variable for the element we want to click on
for (WebElement we : children)    // loop through all our <rect> elements
{
    if (we.isDisplayed())
    {
        elementToClick = we;      // save the <rect> element to our variable
        break;                    // stop iterating
    }
}

if (elementToClick != null)       // check we have a visible <rect> element
{
    elementToClick.click();
}
else
{
    // Handle case if no displayed rect elements were found
}

10-07 19:04
查看更多