gpt4 book ai didi

java - 无法使用 Jsoup 从表中获取特定数据

转载 作者:行者123 更新时间:2023-12-01 21:08:27 24 4
gpt4 key购买 nike

这是我编写的代码片段:

String url = "https://www.premierleague.com/tables";

doc = Jsoup.connect(url).get();
table = doc.select("table").first();

rank = table.select("td[id=tooltip]").iterator(); //Position
team = table.select("td[class=team]").iterator(); //Club
points = table.select("td[class=points]").iterator(); //Points

我可以获取位置、俱乐部和积分等数据,因为我可以使用类(class)名称或 ID 来识别它们,但我无法获取其他数据,如比赛、获胜、平局、失利、GF、GA、GD 等

有人可以帮助我吗?

最佳答案

您可以根据结构使用选择器,请参阅此示例了解列中的第一个条目won:http://try.jsoup.org/~camnKp8NJYL0meyfIRXEtV8E5B4

要获得正确的选择器,您可以使用 Google Chrome 中的开发者工具 (f12),右键单击“元素”选项卡中的某个元素,然后选择复制 -> 复制选择器

Iterator<Element> gamesPlayed = table.select("tbody tr > td:nth-child(4)").iterator();
Iterator<Element> gamesWon = table.select("tbody tr > td:nth-child(5)").iterator();
Iterator<Element> gamesDrawn = table.select("tbody tr > td:nth-child(6)").iterator();
Iterator<Element> gamesLost = table.select("tbody tr > td:nth-child(7)").iterator();

或者逐行解析表格并存储单元格值,如下例所示:

示例代码

String userAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36";
String url = "https://www.premierleague.com/tables";

Document doc;
String position, club, played, won;

try {
doc = Jsoup.connect(url).userAgent(userAgent).get();

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

for (Element row : table.select("tr")) {

Elements cells = row.select("td");

if(cells.size()<5) continue;

position = cells.get(1).select(".value").first().text();
club = cells.get(2).select(".long").first().text();
played = cells.get(3).text();
won = cells.get(4).text();

System.out.println(position + " " + " " + club + "\n\tplayed: " + played + " won: " + won);

}
} catch (IOException e) {
e.printStackTrace();
}

输出

1  Chelsea
played: 21 won: 17
2 Arsenal
played: 22 won: 14
3 Tottenham Hotspur
played: 22 won: 13
4 Liverpool
played: 22 won: 13
5 Manchester City
played: 22 won: 13
...

关于java - 无法使用 Jsoup 从表中获取特定数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41791894/

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