簡體   English   中英

使用 jsoup 提取信息

[英]Extracting information using jsoup

嗨,我是使用 JSoap 和 html 的新手。 我目前正在嘗試從游戲統計網站獲取信息,但在<h1></h1>之間獲取信息時遇到問題。

Document document = Jsoup.connect("https://na.wildstats.gg/en/profile/60ae4f204a9aa2000f3d5f33").get();
Elements winRates = document.getElementsByClass("text-center m-0");
String html = winRates.text();


System.out.println(winRates);
System.out.println(html);
System.out.println("test");

output:

<h1 class="text-center m-0" id="battleStats_WinRate"></h1>
<h1 class="text-center m-0" id="battleStats_MVP"></h1>
<h1 class="text-center m-0" id="battleStats_Played"></h1>
test

在網站上,當我檢查它時,有一個百分比,MVPS 的數量和<h1></h1>之間的比賽,但我沒有顯示出來。 我想知道如何獲得這些數字。 我已經能夠得到球員的簽名和排名和水平。

Jsoup 用於靜態或非常簡單的 html 站點。

Complex sites in the first http request download a basic or empty index.html and then using ajax, get the information from remote services like rest apis or microservices that returns json.

這就是為什么,soups 會返回那個空的 html。

解決方案 1

使用另一個使用內存中瀏覽器的框架。 這種框架能夠等到ajax 獲得信息,然后您將獲得預期值:

  • puppeteer.js
  • casper.js
  • sinon.js

解決方案 2

如果您的唯一目標是獲取數據,您可以使用您喜歡的瀏覽器的開發者控制台並識別 http 服務,該服務以 json 格式返回您的游戲數據。 之后,通過非常簡單的 http 連接,您將獲得游戲數據

解決方案 3

使用 selenium 和無頭瀏覽器獲取您的數據,等待 ajax 響應。

此代碼將使用 JSoup 和 Regex 命名組來獲取三種類型的戰斗統計數據allBattlesnormalBattlesrankedBattles與所有屬性

Document document = Jsoup.connect("https://na.wildstats.gg/en/profile/60ae4f204a9aa2000f3d5f33").get();
Elements elements = document.select("script");
Pattern parserPattern = Pattern.compile("'(?<BATTLE>[a-zA-Z]+)': [{](?<ATTRIBUTES>[\n 'a-zA-Z0-9+:\"0-9a-zA-Z,.]+)[};]");
Matcher matcher = parserPattern.matcher(elements.toString());
while (matcher.find()) {
    String battleType = matcher.group("BATTLE");
    System.out.println("Battle Type: " + battleType);
    String[] attributesLines = matcher.group("ATTRIBUTES")
                    .replaceAll(",\n", "\n")
                    .split("\n");
    for (String line : attributesLines) {
        String[] keyValue = line.trim().split(":");
        if (keyValue.length != 2) continue;
        String key = keyValue[0];
        String value = keyValue[1];
        System.out.println("\t" + key + " : " + value);
    }
}

output 將是

在此處輸入圖像描述

然后,您可以為每場戰斗創建一個 class 並使用名稱和 map 的屬性來表示結果並在 UI 中使用它們

public class Battle {

    private String name;
    private Map<String, String> attributes;

    ...
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM