selenium-webdriver - 获取 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("-----------------------------------------------------------------------------");
谁能告诉我,为什么我会收到此错误。
解决方案
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"));
)
推荐阅读
- google-cloud-platform - 创建公共 Google Cloud 映像(或 machineImage)
- sql-server - 如何在 6 个月前删除表的分区
- javascript - 如何将包含 html 内容的变量打印为字符串?
- reactjs - 在自定义登录页面上引发错误时下一个身份验证“凭据”重定向
- c# - 如何修改 oauth 响应?
- python - Django:连接社交媒体本地用户,但不允许使用社交媒体凭据登录
- c++ - 移动赋值运算符没有移动我的 shared_ptr
- laravel - GET请求结果到流明8中的CORS错误
- cmake - 如何覆盖/附加 CMAKE_C_CFLAG
- reactjs - 在 reactjs 中,单个组件中的多个 api 调用由于状态更改而导致不必要的渲染