2013-08-16 41 views
0

我想提取特定標記下的幾個元素 我有一堆<h5>,我想用它們正下方的<h6><table>進行提取。 我遇到的問題是: a)我有幾個<h5>標籤 b)<h6><table>不是<h5>的孩子/兄弟姐妹。因此例如h5 > table將不起作用。jsoup提取特定標記下的元素

所以我想獲得在最後的是: 從這個網站: http://tcat.nextinsight.com/routes.php?mrnid=453

路線13週一 - 週五,<h6>入站和桌子,以及 路線13週一 - 週五, <h6>出站和表。

一旦我有整個表我可以使用這個例子How to get a table from an html page using JAVA與表

樣本結構的工作:(還可以在給定的URL找到)

<table width="890" border="0" cellspacing="3"> 
     <tr> 
      <td colspan="20" bgcolor="#8cd2ef" class="heading"><h6>Outbound from center of Ithaca</h6></td> 
     </tr> 
     <br><h5>Route 13 - Saturday</h5><tr class="tableSub"><td>Green @ Commons</td> 
<td>Seneca @ Commons</td> 
<td>Third @ Hancock</td> 
<td>Aldi</td> 
<td>Lake @ Ithaca HS</td> 
<td>Stewart Park</td> 
<td>Shops at Ithaca Mall @ Sears</td> 
</tr> 
+0

你可以發佈一個樣本結構? – dcanh121

+0

是的。也可以在給定的URL http://tcat.nextinsight.com/routes.php?mrnid=453找到 – Quantico

回答

1

選擇器:

h5:contains(Route 13 Monday - Friday) + table 

使用,如:

Elements tables = doc.select("h5:contains(Route 13 Monday - Friday) + table"); 

將爲您帶來每個表格前面有<h5>的內容"Route 13 Monday - Friday"

檢查使用您提供的URL工作片段:

public static void main(String[] args) throws Exception { 
    Document doc = Jsoup.connect("http://tcat.nextinsight.com/routes.php?mrnid=453").get(); 
    System.out.println(doc.title()); 
    Elements tables = doc.select("h5:contains(Route 13 Monday - Friday) + table"); 
    for (Element table : tables) { 
     System.out.println(table); 
     System.out.println("#\n#\n#\n#"); 
    } 
}