首页 > 解决方案 > 获取 java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 异常

问题描述

我收到此错误 java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 这是我的代码。

WebElement Case_table = driver.findElement(By.id("ServiceCommunityTemplate")); WebElement tablebody= Case_table.findElement(By.tagName("tbody"));

    List<WebElement> rows = tablebody.findElements(By.tagName("tr"));
    Thread.sleep(12000);

    int count = rows.size();
    System.out.println("ROW COUNT : "+count);

    List<WebElement> colHeaderName = rows.get(0).findElements(By.tagName("th"));
    List<WebElement> colHeader = driver.findElements(By.xpath(".//*[@id='ServiceCommunityTemplate']//table/thead/tr[2]/th"));
    System.out.println("total number of Columns are : " + colHeader.size());
    System.out.println("---------------");
    int colcount = colHeader.size();



        for(int i=1; i<count-1; i++){
            List<WebElement> colVals = rows.get(i).findElements(By.tagName("th"));
            for(int j=0; j<colcount-1; j++){
                    System.out.print(colVals.get(j).getText()+ "\t");

                }
            System.out.println("");
            System.out.println("-----------------------------------------------------------------------------");

谁能告诉我,为什么我会收到此错误。

标签: selenium-webdriverautomation

解决方案


java.lang.IndexOutOfBoundsException当您尝试从列表中获取元素但列表没有具有给定索引的元素时抛出。

从您的例外中可以清楚地看出,您正在尝试获取索引为 0 的元素(即第一个元素),但列表大小为 0(即空列表)。

它可以在线发生

List<WebElement> colHeaderName = rows.get(0).findElements(By.tagName("th"));

如果您无法tr在元素中找到带有标签名称的 WebElement tableBody(List<WebElement> rows = tablebody.findElements(By.tagName("tr"));

或排队

System.out.print(colVals.get(j).getText()+ "\t");

如果您无法th在其中一行中找到任何元素,则可能会发生这种情况 ( List<WebElement> colVals = rows.get(i).findElements(By.tagName("th")); )


推荐阅读