如何使用JSOUP提取表

时间:2017-04-18 11:28:06

标签: android html-table jsoup html-parsing

我正在编写Android应用并尝试弄清楚如何构建我的调用以从此网页获取表格数据:http://uk.soccerway.com/teams/scotland/saint-mirren-fc/1916/squad/

我已经从JSOUP网站上阅读了这本食谱,但因为我没有使用过这个库,所以我有点卡住了。我想出了类似的东西:

doc = Jsoup.connect("http://uk.soccerway.com/teams/scotland/saint-mirrenfc/1916/squad/").get();
Element squad = doc.select("div.squad-container").first(); Element
Elements table = squad.select("table squad sortable");

正如你所看到的,我还没有获得球员统计数据。我认为下一步应该是将新的Element对象指向" tbody"标签内的"表格可排序"? 我知道一旦我设法读取表然后读取循环内的每一行,我将不得不使用for循环。

不幸的是,对于没有经验的人来说,表格结构有点复杂,所以我真的很感激一些建议!

1 个答案:

答案 0 :(得分:0)

基本上每行都有以下选择器 -
#page_team_1_block_team_squad_3-table > tbody:nth-child(2) > tr:nth-child(X)其中X是行的编号(从1开始) 一种方法是迭代行并提取信息:

String url = "http://uk.soccerway.com/teams/scotland/saint-mirren-fc/1916/squad/";
String userAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0";
Document doc = null;
try {
    doc = Jsoup.connect(url)
            .userAgent(userAgent)
            .get();
} catch (IOException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
}
int i = 1;
Elements row;
do {
    row = doc.select("#page_team_1_block_team_squad_3-table > tbody:nth-hild(2) > tr:nth-child(" + i + ")");
    for (Element el : row) {
        System.out.print(el.select(".shirtnumber").text() + " ");
        System.out.println(el.select(".name").text());
        i++;
    }
} while (row != null); 

这将打印每个玩家的号码和名称。由于我不想计算行数(并保持程序易于进行更改),我想使用do...while循环 - 我将迭代为行存在(或非空)。
我得到的输出:

  

1 J. Langfield   21 B. O' Brien   28 R. Willison   2 S. Demetriou   3 G. Irvine   4 A.韦伯斯特   ...

使用浏览器的开发者工具获取其他列的名称,并使用它来获取所需的所有信息。