在Selenium webdriver中跳过SVG条形图上的元素

时间:2014-12-16 14:23:43

标签: java eclipse selenium selenium-webdriver webdriver

我在java中为selenium构建了一个方法,我想点击SVG条形图并点击前3个栏(下面的截图) Screenshot 我通过实现以下代码完成了这项工作:

    public static void barChartSelector(InternetExplorerDriver driver)
{
    genericControls.waitCommands.fluentWaitOnBarChartSelector(driver);
    WebElement parent = driver.findElement(By.className("highcharts-series-group"));
    genericControls.waitCommands.fluentWaitOnBarChartSelector(driver);
    List<WebElement> children = parent.findElements(By.tagName("rect"));
    genericControls.waitCommands.fluentWaitOnBarChartSelector(driver);
    children.get(0).click();
    children.get(1).click();
    children.get(2).click();
    genericControls.waitCommands.fluentWaitOnRelationalBarGraphDisplay(driver);
}

但是,我发现我有时会收到此错误:

"Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 2, Size: 0
    at java.util.ArrayList.rangeCheck(Unknown Source)
    at java.util.ArrayList.get(Unknown Source)
    at genericControls.graphSelectors.relationalBarChartSelector(graphSelectors.java:34)
    at Reports.collections.breachReportCompletedFunctions(collections.java:30)
    at Reports.programMain.main(programMain.java:37)"

看起来当我运行'get'命令时,图表并不总是在页面之间的索引相同,因此在某些页面上它会起作用,而某些页面会失败。我的想法是我需要实现一个'for'循环,这样我仍然可以运行'children.get(X).click();'事件,但如果代码找不到第一个事件,它会循环,直到找到返回结果的'get'命令。

请有人可以告诉我如何将上面的代码转换为'for'循环,以便它可以查找任何可能符合条件的'children'元素?这有助于我理解将来如何实现这一目标。

1 个答案:

答案 0 :(得分:1)

我觉得问题出现在这里:     列出children = parent.findElements(By.tagName(“rect”));

IndexOutOfBoundsException被抛出,因为children并不总是包含3个Web元素。

尝试替换为:

List<WebElement> children = parent.findElements(By.tagName("rect"));
genericControls.waitCommands.fluentWaitOnBarChartSelector(driver);
for (WebElement child : children) {
    if (children.indexOf(child) > 2)
        break;
    child.click();
}

注意,我假设可能有超过3个“rect”WebElements,并且您只想点击第一个.3。如果要单击所有rect元素,请删除if语句。