2017-01-22 61 views
0

下面的代碼片段,我寫來從表的具體數據:無法使用Jsoup

​​

我可以取像的位置,俱樂部和點的數據,因爲我可以用類名或ID,但我確定他們無法獲取像Played,Won,Draw,Loss,GF,GA,GD等其他數據。

有人可以幫我嗎?

+0

是這解決了嗎?然後請接受給定的答案,否則在評論中發佈後續問題。關於「離題」:不同意,問題是:如何選擇沒有id或class的元素,並在問題中給出所有信息。 –

+1

接受的答案,對於遲到的回覆抱歉。是的,這不是脫離主題,同意。 – CodePlorer

回答

3

您可以使用基於結構的選擇,看到這個例子中列第一個條目贏得http://try.jsoup.org/~camnKp8NJYL0meyfIRXEtV8E5B4

要獲得選擇的權利,你可以使用谷歌瀏覽器的開發者工具(F12),右鍵點擊在「元素」選項卡中的元素上,然後選擇Copy -> Copy selector

Iterator<Element> gamesPlayed = table.select("tbody tr > td:nth-child(4)").iterator(); 
Iterator<Element> gamesWon = table.select("tbody tr > td:nth-child(5)").iterator(); 
Iterator<Element> gamesDrawn = table.select("tbody tr > td:nth-child(6)").iterator(); 
Iterator<Element> gamesLost = table.select("tbody tr > td:nth-child(7)").iterator(); 

替代地通過行解析錶行和單元的值存儲爲在下面的例子:

示例代碼

String userAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36"; 
String url = "https://www.premierleague.com/tables"; 

Document doc; 
String position, club, played, won; 

try { 
    doc = Jsoup.connect(url).userAgent(userAgent).get(); 

    Element table = doc.select("table").first(); 

    for (Element row : table.select("tr")) { 

     Elements cells = row.select("td"); 

     if(cells.size()<5) continue; 

     position = cells.get(1).select(".value").first().text(); 
     club = cells.get(2).select(".long").first().text(); 
     played = cells.get(3).text(); 
     won = cells.get(4).text(); 

     System.out.println(position + " " + " " + club + "\n\tplayed: " + played + " won: " + won); 

    } 
} catch (IOException e) { 
    e.printStackTrace(); 
} 

輸出

1 Chelsea 
    played: 21 won: 17 
2 Arsenal 
    played: 22 won: 14 
3 Tottenham Hotspur 
    played: 22 won: 13 
4 Liverpool 
    played: 22 won: 13 
5 Manchester City 
    played: 22 won: 13 
... 
+0

你能用一個例子解釋一下在我的代碼中如何使用它嗎? – CodePlorer

+0

@CodePlorer查看更新的答案。 –

+0

但是這對我沒有用處,我需要映射到GUI元素的各個字段的數據。例如,textField1 - >匹配球隊排名1,textField2 - >匹配球隊排名2。我可以很容易地用Iterator做next()...你能幫忙嗎? – CodePlorer