使用Java从Web页面中获取信息?

时间:2018-06-18 17:15:04

标签: java http web-scraping parameters response

我正在尝试从网页中提取数据,例如,假设我想从chess.org获取信息。

我知道玩家的ID是25022,这意味着我可以请求 http://www.chess.org.il/Players/Player.aspx?Id=25022

在该页面中我可以看到该玩家的真实身份ID = 2821109 由此,我可以请求此页面:
http://ratings.fide.com/card.phtml?event=2821109

从中我可以看出stdRating = 1602。

如何从Java中的给定“localID”输入中获取“stdRating”输出?

(localID,fideID和stdRating是我用来澄清问题的辅助参数)

2 个答案:

答案 0 :(得分:1)

您可以尝试使用univocity-html-parser,它非常易于使用,并且避免了很多意大利面条式代码。

例如,要获得标准等级,您可以使用以下代码:

public static void main(String... args) {
    UrlReaderProvider url = new UrlReaderProvider("http://ratings.fide.com/card.phtml?event={EVENT}");
    url.getRequest().setUrlParameter("EVENT", 2821109);

    HtmlElement doc = HtmlParser.parseTree(url);

    String rating = doc.query()
            .match("small").withText("std.")
            .match("br").getFollowingText()
            .getValue();

    System.out.println(rating);
}

哪个产生值1602

但是通过查询单个节点并尝试将所有部分拼接在一起来获取数据并不是一件容易的事。

我扩展了代码,以说明如何使用解析器将更多信息添加到记录中。在这里,我为玩家创建了记录及其排名细节,这些记录可在第二页的表格中找到。我花了不到1小时的时间完成了此任务:

public static void main(String... args) {
    UrlReaderProvider url = new UrlReaderProvider("http://www.chess.org.il/Players/Player.aspx?Id={PLAYER_ID}");
    url.getRequest().setUrlParameter("PLAYER_ID", 25022);

    HtmlEntityList entities = new HtmlEntityList();
    HtmlEntitySettings player = entities.configureEntity("player");
    player.addField("id").match("b").withExactText("מספר שחקן").getFollowingText().transform(s -> s.replaceAll(": ", ""));
    player.addField("name").match("h1").followedImmediatelyBy("b").withExactText("מספר שחקן").getText();
    player.addField("date_of_birth").match("b").withExactText("תאריך לידה:").getFollowingText();
    player.addField("fide_id").matchFirst("a").attribute("href", "http://ratings.fide.com/card.phtml?event=*").getText();

    HtmlLinkFollower playerCard = player.addField("fide_card_url").matchFirst("a").attribute("href", "http://ratings.fide.com/card.phtml?event=*").getAttribute("href").followLink();
    playerCard.addField("rating_std").match("small").withText("std.").match("br").getFollowingText();
    playerCard.addField("rating_rapid").match("small").withExactText("rapid").match("br").getFollowingText();
    playerCard.addField("rating_blitz").match("small").withExactText("blitz").match("br").getFollowingText();
    playerCard.setNesting(Nesting.REPLACE_JOIN);

    HtmlEntitySettings ratings = playerCard.addEntity("ratings");
    configureRatingsBetween(ratings, "World Rank", "National Rank ISR", "world");
    configureRatingsBetween(ratings, "National Rank ISR", "Continent Rank Europe", "country");
    configureRatingsBetween(ratings, "Continent Rank Europe", "Rating Chart", "continent");

    Results<HtmlParserResult> results = new HtmlParser(entities).parse(url);
    HtmlParserResult playerData = results.get("player");
    String[] playerFields = playerData.getHeaders();

    for(HtmlRecord playerRecord : playerData.iterateRecords()){
        for(int i = 0; i < playerFields.length; i++){
            System.out.print(playerFields[i] + ": " + playerRecord.getString(playerFields[i]) +"; ");
        }
        System.out.println();

        HtmlParserResult ratingData = playerRecord.getLinkedEntityData().get("ratings");
        for(HtmlRecord ratingRecord : ratingData.iterateRecords()){
            System.out.print(" * " + ratingRecord.getString("rank_type") + ": ");
            System.out.println(ratingRecord.fillFieldMap(new LinkedHashMap<>(), "all_players", "active_players", "female", "u16", "female_u16"));
        }
    }
}

private static void configureRatingsBetween(HtmlEntitySettings ratings, String startingHeader, String endingHeader, String rankType) {
    Group group = ratings.newGroup()
            .startAt("table").match("b").withExactText(startingHeader)
            .endAt("b").withExactText(endingHeader);

    group.addField("rank_type", rankType);

    group.addField("all_players").match("tr").withText("World (all", "National (all", "Rank (all").match("td", 2).getText();
    group.addField("active_players").match("tr").followedImmediatelyBy("tr").withText("Female (active players):").match("td", 2).getText();
    group.addField("female").match("tr").withText("Female (active players):").match("td", 2).getText();
    group.addField("u16").match("tr").withText("U-16 Rank (active players):").match("td", 2).getText();
    group.addField("female_u16").match("tr").withText("Female U-16 Rank (active players):").match("td", 2).getText();
}

输出将是:

id: 25022; name: יעל כהן; date_of_birth: 02/02/2003; fide_id: 2821109; rating_std: 1602; rating_rapid: 1422; rating_blitz: 1526; 
 * world: {all_players=195907, active_players=94013, female=5490, u16=3824, female_u16=586}
 * country: {all_players=1595, active_players=1024, female=44, u16=51, female_u16=3}
 * continent: {all_players=139963, active_players=71160, female=3757, u16=2582, female_u16=372}

希望有帮助

披露:我是这个图书馆的作者。它是商业上的封闭源代码,但是可以节省很多开发时间。

答案 1 :(得分:0)

正如@Alex R指出的那样,你需要一个网络刮痧库。
他推荐的那个JSoup非常强大,并且在Java中非常常用于此任务,至少在我的经验中是这样。

您首先需要构建一个获取页面的文档,例如:

int localID = 25022; //your player's ID.
Document doc = Jsoup.connect("http://www.chess.org.il/Players/Player.aspx?Id=" + localID).get();

从这个Document对象中,您可以获取大量信息,例如您请求的FIDE ID,遗憾的是您链接的网页非常简单,而且您需要基本上去通过页面上的每个链接查找相关链接,例如:

Elements fidelinks = doc.select("a[href*=fide.com]");

Elements对象应该为您提供链接到包含文本fide.com的所有链接的列表,但您可能只需要第一个,例如:

Element fideurl = doc.selectFirst("a[href=*=fide.com]");

从那时起,我不想为你编写所有代码,但希望这个答案可以作为一个很好的起点!

您可以通过调用Element对象上的text()方法来获取ID,但您也可以通过调用Element.attr('href')来获取链接

您可以使用css选择器获取其他值 div#main-col table.contentpaneopen tbody tr td table tbody tr td table tbody tr:nth-of-type(4) td table tbody tr td:first-of-type,它会特别为你提供std分数,至少是标准的css,所以这也适用于jsoup。