2015-02-24 100 views
0

我有一個像這樣的表,我想要解析以獲取數據代碼值row.id和表的第二和第三列。JSoup如何解析表3行

<table> 
    <tr class="id" data-code="100"> 
     <td></td> 
     <td>18</td> 
     <td class="name">John</td> 
    <tr/> 
    <tr class="id" data-code="200"> 
     <td></td> 
     <td>21</td> 
     <td class="name">Mark</td> 
    <tr/> 
</table> 

我想打印出來。

100, 18, John 
200, 21, Mark 

我曾嘗試以下建議,從這個線程,但它不是選擇什麼how to parse a table from HTML using jsoup

URL url = new URL("http://www.myurl.com"); 
Document doc = Jsoup.parse(url, 3000); 

Element tables = doc.select("table[class=id]"); 

for(Element table : tables) 
{ 
    System.out.println(table.toString()); 
} 

編輯:使用Jsoup.connect(也嘗試過),而不是解析()

Document doc = null; 
try 
{ 
    doc = Jsoup.connect("http://www.myurl.com").get(); 
} 
catch (IOException e) 
{ 
    e.printStackTrace(); 
} 
+0

表沒有一個類別「id」 ......?嘗試tr [class = id] – 2015-02-24 13:20:59

+0

它不工作,我已經嘗試過'doc.select(「table tr.id」)''和table tr [class = id]「)' – Clumbsyx 2015-02-24 13:25:22

+0

這裏工作正常...錯誤是大概在前兩行...... println(doc)輸出什麼東西? – 2015-02-24 13:35:23

回答

0

請試試像這樣:

URL url = new URL("http://www.myurl.com"); 
Document doc = Jsoup.parse(url, 3000); 
// This should work now 
Element tables = doc.select("table tr .id"); 
// This propably should work too 
Element tables2 = doc.select("table tr[class*=id]"); 

for(Element table : tables) 
{ 
    System.out.println(table.toString()); 
} 

從技術文檔:

公共元素選擇(字符串cssQuery)查找匹配 選擇CSS查詢元素,該元素爲出發上下文。匹配的 元素可能包含此元素或其任何子元素。這個 方法通常比DOM類型 getElementBy *方法更強大,因爲可以組合多個過濾器,例如: •el.select(「a [href]」) - 查找鏈接(帶有href屬性的標籤) •el.select(「a [href * = example.com]」) - 查找指向 example.com(鬆散地)的鏈接

請參閱Selector中的查詢語法文檔。

參數:cssQuery - 一個選擇類似CSS的查詢返回:與查詢匹配的元素 (空如果沒有匹配)

+0

更改元素....到元素..... – Galunid 2015-02-24 14:22:21

+0

謝謝你的作品。如何獲得之間的文本約翰' – Clumbsyx 2015-02-24 14:25:22

+0

doc.select(「table tr .id td」)。text();我的事。 – Galunid 2015-02-24 14:27:55