jSoup获取表中每个元素的链接

时间:2014-11-09 11:02:36

标签: java jsoup

我正在尝试获取http://www.statto.com/football/stats/england/premier-league表格中每个小组的链接。目前我的代码只获取团队名称,但似乎将每个团队输出为一个字符串......我希望每个元素都作为链接输出,因此“切尔西”将是“http://www.statto.com/football/teams/chelsea”。

我目前的代码:

        Document doc = Jsoup.connect(
            "http://www.statto.com/football/stats/england/premier-league").get();

    Element tableHeader = doc.select("table[class=tabBG]").first();
    for (Element element : tableHeader.children()) {
        // Here you can do something with each element
            String team = element.select("td:eq(1) a").text();
            System.out.println(team);

        }
    }

有人知道如何获取表格中每个项目的链接作为单个字符串输出吗?

谢谢,

罗布

1 个答案:

答案 0 :(得分:0)

我现在已经找到了解决问题的方法,下面是有效的代码:

Document doc = Jsoup.connect(
            "http://www.statto.com/football/stats/germany/bundesliga").get();

    Element tableHeader = doc.select("tbody").first();
    for (Element element : tableHeader.children()) {
        // Here you can do something with each element
        if (element.select("td:eq(1)").html().contains("acronym") != false || element.select("td:eq(1)").html().contains("nbsp") != false){
            //do nothing
        } else {
            String teamname = element.select("td:eq(1) a").html();
            String team = element.select("td:eq(1)").toString()
                    .replace("<a href=\"", "http://www.statto.com").replace(" class=\"b\">", "").replace(teamname, "").replace("<td class=\"steam\">", "").replace("\"</a></td>", "");


            System.out.println(team);

        }

    }

这给了我以下输出:

http://www.statto.com/football/teams/bayern-munich
http://www.statto.com/football/teams/vfl-wolfsburg
http://www.statto.com/football/teams/borussia-monchengladbach
http://www.statto.com/football/teams/hannover-96
http://www.statto.com/football/teams/tsg-hoffenheim
http://www.statto.com/football/teams/bayer-leverkusen
http://www.statto.com/football/teams/augsburg
http://www.statto.com/football/teams/mainz
http://www.statto.com/football/teams/paderborn-07
http://www.statto.com/football/teams/fc-cologne
http://www.statto.com/football/teams/schalke-04
http://www.statto.com/football/teams/eintracht-frankfurt
http://www.statto.com/football/teams/sc-freiburg
http://www.statto.com/football/teams/hertha-bsc-berlin
http://www.statto.com/football/teams/werder-bremen
http://www.statto.com/football/teams/sv-hamburg
http://www.statto.com/football/teams/vfb-stuttgart
http://www.statto.com/football/teams/borussia-dortmund