簡體   English   中英

Jsoup-網站上表格數據的排列

[英]Jsoup - arrangement of table data from website

我想從https://ms.wikipedia.org/wiki/馬來西亞獲取表格。 這是我要從網站上獲得的表格。

表

但是結果不是我想要的。

myResult

我有2個問題

第一個問題是如何將它們像表格一樣排列, 列的排列方式與圖片中的表格相似。 以下是我如何獲取數據的源代碼。

String URL = "https://ms.wikipedia.org/wiki/Malaysia";
Document doc = Jsoup.connect(URL).get();
Elements trs = doc.select("#mw-content-text > div > table:nth-child(148)");
String currentRow = null;
for (Element tr : trs){
    Elements tdDay = tr.select("tr:has(th)");
        currentRow = tdDay.text();
        System.out.print(currentRow);
}

第二個問題來自我的源代碼,這是從所有元素(例如網站https://ms.wikipedia.org/wiki/馬來西亞)中的元素中抓取特定數據的最佳方法嗎

Elements trs = doc.select("#mw-content-text > div > table:nth-child(148)");

因為從網站上,有3個表類,名稱為wikitable。 <table class="wikitable"> 那么,如何才能只調用特定的表呢?

由於您提供的網站中包含一些wikitable 因此,您可以嘗試從表中找出數據的選擇器,而我發現有<td><th>

for (int i = x; i < x; i++) {
    Elements trs = doc.select("#mw-content-text > div > table:nth-child(148) > tbody > tr:nth-child(" + i + ") > th");
    Elements tds = doc.select("#mw-content-text > div > table:nth-child(148) > tbody > tr:nth-child(" + i + ") > td");

試試這個,而for循環中的x是表中的行數,這樣它就可以抓取數據

public static void main(String[] args) throws IOException{
    String URL = "https://ms.wikipedia.org/wiki/Malaysia";
    Document doc = Jsoup.connect(URL).get();
    //Select the table which is under the header containing "Trivia" 
    //having the value "wikitable" for the class attribute
    Element table = doc.select("h2:contains(Trivia)+[class=\"wikitable\"]").first();
    //then select each row of the table 
    Elements trs = table.select("tr");
    //for each row get first and second child corresponding to column 1 and two of table
    for (Element tr : trs){
        Element th = tr.child(0);
        Element td = tr.child(1);
        System.out.printf("%-40s %-40s%n",th.text(), td.text());
    }
}

暫無
暫無

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

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