2014-11-01 224 views
-1

假設我有以下的HTMLJsoup - 提取數據

<table id="tableMain"> 
    <tr> 
    <td class="location">Location A text</td> 
    </tr> 
    <tr> 
    <td> 
    <table id="titleList"> 
    <tr> 
     <td class="title">Title A.A</td> 
     <td class="date">date</td> 
     <td class="time">time</td> 
    </tr> 
    </table> 
    <table id="titleList"> 
    <tr> 
     <td class="title">Title A.B</td> 
     <td class="date">date</td> 
     <td class="time">time</td> 
    </tr> 
    </table> 
    <table id="titleList"> 
    <tr> 
     <td class="title">Title A.C</td> 
     <td class="date">date</td> 
     <td class="time">time</td> 
    </tr> 
    </table> 
    </td> 
    </tr> 

    <tr> 
    <td class="location">Location B text</td> 
    </tr> 
    <tr> 
    <td> 
    <table id="titleList"> 
    <tr> 
     <td class="title">Title B.A</td> 
     <td class="date">date</td> 
     <td class="time">time</td> 
    </tr> 
    </table> 
    <table id="titleList"> 
    <tr> 
     <td class="title">Title B.B</td> 
     <td class="date">date</td> 
     <td class="time">time</td> 
    </tr> 
    </table> 
    <table id="titleList"> 
    <tr> 
     <td class="title">Title B.C</td> 
     <td class="date">date</td> 
     <td class="time">time</td> 
    </tr> 
    </table> 
    </td> 
    </tr> 
</table> 

有兩個位置:位置A和位置B的每個位置都有,其中每個列表包含標題,日期和時間多個標題列表。

我能夠提取位置,但我不知道如何提取標題列表並映射到其各自的位置。

我這是怎麼提取的位置:

File input = new File("/home/user/htmlcontent.txt"); 
Document doc = Jsoup.parse(input, "UTF-8", "http://www.example.com"); 

Elements elements = doc.select("table#tableMain").select("location"); 
for (Element e: elements) { 
    system.out.println(e.text()); 
} 

回答

1

考慮這個例子:

Document document = Jsoup.parse(html); 

    Elements elements = document.select("#tableMain tr:has(td.location) + tr"); 

    for (Element element : elements) { 
     String location = element.previousElementSibling().select("td.location").text(); 

     System.out.printf("Current location: '%s'%n", location); 

     Elements titleLists = element.select("#titleList > tbody > tr"); 

     for (Element tr : titleLists) { 
      String title = tr.select("td.title").text(); 
      String date = tr.select("td.date").text(); 
      String time = tr.select("td.time").text(); 

      System.out.printf("Title: %s, Date: %s, Time: %s%n", title, date, time); 
     } 
    } 

您可以在這裏找到完整的代碼 - https://gist.github.com/wololock/b0e31cb174123d463e3e

在這個例子中最重要的部分是用於選擇不包含位置信息的行的選擇器:

document.select("#tableMain tr:has(td.location) + tr") 

爲了達到這個目的,我們首先要求那些有td.locationtr s,從那時起我們要求兄弟元素... + tr。從這一點我們可以看到嵌套#titleList表的行。你開始選擇從嵌套表數據,然後可以提取與位置信息:

element.previousElementSibling().select("td.location").text() 

我使用迭代過:

element.select("#titleList > tbody > tr") 

並選擇單個數據的時間,例如標題,日期,時間。這不是最有效的解決方案,它取決於您的源html中可能有多少行。儘管爲大量數據進行優化不應該有任何問題。

我希望這會幫助你:)

+0

嘿@szymon,謝謝你的解釋。它有助於。與您的幫助我能夠提取我需要的信息。 – nuttynibbles 2014-11-02 02:20:45

+0

太好了,我很高興能幫到你。保重! – 2014-11-02 08:57:43