java - 使用 jsoup get() 函数时出现 IndexOutOfBoundsException
问题描述
基本上,我的函数从https://meta.wikimedia.org/wiki/Table_of_Wikimedia_projects加载网页并获取表格,以便在其行中的某个单元格不为空时打印语言的名称。这是代码:
public static void getLanguagesFromProject(String project) {
String html = "https://meta.wikimedia.org/wiki/Table_of_Wikimedia_projects";
try {
Document doc = Jsoup.connect(html).get();
Elements tableElements = doc.select("table.wikitable.sortable");
Elements rows = tableElements.select("tr");
int column = 0;
switch (project) {
case "Wikipedia":
column = 3;
break;
case "Wiktionary":
column = 4;
break;
case "Wikibooks":
column = 5;
break;
case "Wikinews":
column = 6;
break;
case "Wikiquote":
column = 7;
break;
case "Wikisource":
column = 8;
break;
case "Wikiversity":
column = 9;
break;
case "Wikivoyage":
column = 10;
break;
default:
break;
}
for (Element row : rows) {
Elements cols = row.select("td");
System.out.println(cols.get(column).text());
}
} catch (Exception e) {
e.printStackTrace();
}
}
发生的情况是我收到 IndexOutOfBoundsException 错误,特别是在 for 循环的第二个语句中:System.out.println(cols.get(column).text());
知道需要做什么吗?编辑:更详细的错误:
java.lang.IndexOutOfBoundsException: Index 3 out-of-bounds for length 0
at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)
at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)
at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:248)
at java.base/java.util.Objects.checkIndex(Objects.java:372)
at java.base/java.util.ArrayList.get(ArrayList.java:440)
at com.company.Main.getLanguagesFromProject(Main.java:76)
at com.company.Main.main(Main.java:11)
解决方案
请注意,您已选择所有<tr>
Elements tableElements = doc.select("table.wikitable.sortable");
Elements rows = tableElements.select("tr");
包括标题中的那些。然后它的第一行将是没有的标题<td>
,然后,在它的第一次迭代中,它在IndexOutOfBoundsException
尝试获取第三个元素时出现异常,<td>
因为它在那里不存在。
只需排除第一个<tr>
标题
// start from 1, exclude 0 which is a header without td's
for (int i = 1; i < rows.size(); i++) {
Elements cols = rows.get(i).select("td");
System.out.println(cols.get(column).text());
}
推荐阅读
- angular - 为什么是
没有在 Angular 7 中显示的数据源 - sql - 如何获得除一列外所有值都相同的两行
- azure-functions - 我们如何计算运行编排功能的总时间
- node.js - 提供所需值时如何修复 mongoose 验证器错误,但 mongoose 无法识别
- python - Keras get_weights() 不返回所有权重
- python - 在 Windows 机器上,安装了 Python 3.7,但似乎 3.6 正在运行
- python - 如何测试比较的用法?
- c - 奇怪的 mktime() 行为
- c# - 剃须刀页面中移动设备的页面不同但路由相同
- python - 如何在每 5 个数字后添加换行符?