如何在Selenium中跳过NoSuchElementException

时间:2014-12-12 10:35:22

标签: java eclipse selenium webdriver

我有一个场景,我想点击图表中的一个栏('回复'),然后显示一个关系条形图('响应"付款优惠(是)"&#39)。当我从关系条形图中单击一个条形时,它会显示一个合同列表。这在下面的屏幕截图中突出显示 Screenshot

我遇到的问题是'回复'图表并未在付款要约(是)'部分。这是一个有效的测试场景,但接下来发生的是右侧的关系条形图没有显示任何数据。此外,当我的selenium代码然后从列表中查找合同但无法找到它时,测试将失败并且出现NoSuchElementException'。我理解为什么会这样做,但我的问题是....有没有一种方法可以调整代码来满足这种情况,这样如果它找不到关系图(右侧图),而且,下表中的合同清单,代码能够跳过这个吗?

我已附上以下代码的详细信息:

1)此方法尝试从表中的列表中打开/关闭合同。是否可以通过某种方式对其进行修改,以便在没有显示合同时(这是一个有效的方案),代码可以跳过NoSuchElementException?

    public static void openCloseContractForReportWithBarChart(InternetExplorerDriver driver) throws InterruptedException {
    String winHandleBefore = driver.getWindowHandle();
    waitCommands.fluentWaitOnContractSelect(driver);

    for(String winHandle : driver.getWindowHandles()) {
       if(!winHandle.equals(winHandleBefore)){
                try{
                    Thread.sleep(4000);
                   }catch(InterruptedException e){
                   }
                driver.switchTo().window(winHandle);
                break;
            }
    }       
    driver.close();
    driver.switchTo().window(winHandleBefore);
}

2)您在上述方法中注意到,我引用了一个' FluentWaitOnContractSelect'方法。详情如下:

    public static void fluentWaitOnContractSelect(InternetExplorerDriver driver)
{

    WebElement selectContractAfterWait = (new WebDriverWait(driver, 15))
            .until(ExpectedConditions.elementToBeClickable(By.xpath(".//*[@id='tabular-breakdown']/table/tbody/tr[1]/td[1]/a")));
    selectContractAfterWait.click();
}

任何帮助都会受到赞赏。

1 个答案:

答案 0 :(得分:1)

据我所知,你不能跳过元素,因为不知道什么时候找不到确切的元素,所以最好的方法是告诉网页驱动程序等到找到下一个元素,请用户下面的代码:

 WebDriverWait wait = new WebDriverWait(webDriver, timeoutInSeconds);
 wait.until(ExpectedConditions.visibilityOfElementLocated(By.id[elementlocator]));
相关问题