2015-02-24 101 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