gpt4 book ai didi

java - 如何在 Java 中读取没有 ID 或 DIV 的 HTML 页面中的表格

转载 作者:行者123 更新时间:2023-11-30 08:14:07 26 4
gpt4 key购买 nike

我想读取一个表格,它是一个 HTML 页面,但它没有任何 id 来检测它。所以网页是这样的one

我想要的只是这张表及其值: enter image description here

在Java中,我想要两个玩家的ArrayList(它们是对象);第一个是“Goal Vittoria”,第二个是“Goal Pareggio”;

 public class Player {

private String surname;
private String team;
}

我已经使用了 JSoup 库,它做得很好,但问题是网页组织得不好,很难阅读所有内容。这就是我能做的:

URL url = new URL("http://www.fantagiaveno.it/goalpartita.asp");
Document doc = Jsoup.parse(url, 3000);

Element table = doc.select("table").first();

Iterator<Element> ite = table.select("td[class=TestoTabella8]").iterator();

ite.next(); // first one is image, skip it
int index = 0;
while(index<30){
Element par = ite.next();
String text = par.text();
int hash = par.hashCode();
if(hash!=292270948){

System.out.println(text);
}


index++;
}

问题是输出不符合我的要求,因为我无法获取标题和/或了解玩家是来自第一种类型(Goal Vittoria)还是第二种类型(Goal Pareggio)。另外,我设置的索引 30 并不总是正确的,因为可以设置更多的球员(Goal Vittoria 和 Goal Pareggio 的 MAX 数量都可以是 10)。有什么建议吗?

最佳答案

The problem is that the output is not as I want, because I can't get the title >and/or understand if the Player is from the first type (Goal Vittoria) or the >second one (Goal Pareggio) Select all the tables and loop through them to check the title. If the title >matches then start your iterator

在您发布的链接中,表格的标题存储在第一行的第一个 td 中。使用 JSoup 选择器获取第一行中第一个 td 的值,然后检查该值是否以 'GOAL VITTORIA' 或 'GOAL PAREGGIO' 开头

    URL url = new URL("http://www.fantagiaveno.it/goalpartita.asp");
Document doc = Jsoup.parse(url, 3000);

Elements elements = doc.body().select(".TitoloTabellaBlu");

for (Element element : elements) {
String val = element.html();
if (val.startsWith("GOAL VITTORIA")) {
Iterator<Element> ite = element.parent().parent().select("td[class=TestoTabella8]").iterator();
ite.next(); // first one is image, skip it
int index = 0;

while (ite.hasNext()) {
//your code here
}
} else if (val.startsWith("GOAL PAREGGIO")) {
Iterator<Element> ite2 = element.parent().parent().select("td[class=TestoTabella8]").iterator();
while (ite2.hasNext()) {

}
}

}

Updated

Also the index I set 30, isn't always correct

如上所述,在迭代器上使用 .hasNext() 方法。

关于java - 如何在 Java 中读取没有 ID 或 DIV 的 HTML 页面中的表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29901319/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com