<td> <tr> <table> 使用 JSoup 解析 a 的第一个和最后一个值



我已经能够成功地使用 JSoup 解析整个页面,但是我在解析表的第一<td>和第一<tr>时遇到了一些挑战。特别是看到表格行数在一天中的变化。

到目前为止,我知道我需要从页面中获取表格,所以我正在使用这个doc.select("table.tabular zebra").toString();(虽然我不知道如何处理表类中的空间,但这是一个单独的问题)。

示例表如下:

<table id="tradesTableE_PPT_L0" class="tabular zebra" style="float:left; margin-right:10px">
<caption>Latest trades</caption>
<thead>
    <tr>
      <th id="tradeTime" title="The time the trade was published">Time</th>
      <th id="tradePrice" title="The trade price">Price</th>
      <th id="tradeVolume" title="Number of shares traded">Volume</th>
      <th id="tradeTotalPrice" title="Total value of bargain">Value</th>
      <th id="bidPrice" title="Best bid at time of trade">Bid</th>
      <th id="askPrice" title="Best ask at time of trade">Ask</th>
      <th id="tradeType" title="Buy/Sell indicator"><a href="#types" style="color=#0000CC">B/S</a></th>
    </tr>
</thead>
<tbody>
  <tr align="right">
  <th>16:22:40</th>
    <td>204p</td>
    <td>2,500</td>
    <td>&pound;5,100</td>
    <td>192.5p</td>
    <td>192.5p</td>
    <td align="center" style='color:blue;'>Buy</td>
  </tr>
  <tr align="right">
  <th>16:05:23</th>
    <td>200p</td>
    <td>2,500</td>
    <td>&pound;5,000</td>
    <td>192.5p</td>
    <td>192.5p</td>
    <td align="center" style='color:blue;'>Buy</td>
  </tr>
  <tr align="right">
  <th>15:59:51</th>
    <td>197p</td>
    <td>1,000</td>
    <td>&pound;1,970</td>
    <td>192.5p</td>
    <td>192.5p</td>
    <td align="center" style='color:blue;'>Buy</td>
  </tr>
</tbody>
</table>

访问表元素可能会变得非常混乱。过去,我不得不使用硒来验证表中的值。我发现将整个表 HTML 解析为开发人员友好的对象有助于我大大简化代码。没有它,代码中有很多混乱的xpath选择器,这使得它难以阅读/维护。

例如:

TableWithHeaders table = MyHtmlUtils.parseTableWithHeaders(dom, "//[id=tradesTableE_PPT_L0]");
assertEquals(3, table.getRowCount());
assertEquals("204p", table.getCellText("Price", 0));
assertEquals("1,000", table.getCellText("Volume", 2));
public interface TableWithHeaders {
   int getRowCount();
   Collection<String> getHeaderNames();
   String getCellText(String header, int row);
   Element getCell(String header, int row);
   ...
}

我得到了答案:

对于第一行:

doc.select("[id^=tradesTableE_]").select("tr").get(1).select("td").get(0).text().toString();

最后一行:

doc.select("[id^=tradesTableE_]").select("tr").last().select("td").get(0).text().toString();

最新更新