【问题标题】:jSoup: Am not being able to correctly parse two consecutive table cells with identical values?jSoup:无法正确解析两个具有相同值的连续表格单元格?
【发布时间】:2016-01-15 02:43:08
【问题描述】:

我的表格(为了更好的可视性而缩短和格式化):

String htmlStr = 
"<table class="xt">
  <tbody>
   <tr><th class="bg-warning" colspan="3">-</th></tr>
   <tr><th class="bg-warning">2014-08-29</th><td>0</td><td>0.00</td><td>0.00</td></tr>
  </tbody>
</table>"

我的代码:

org.jsoup.nodes.Document doc = Jsoup.parse(htmlStr);
xt = doc.select("table.xt").first();
thCols = xt.select("tr").eq(1).select("th").size();
tdCols = xt.select("tr").eq(1).select("td").size();

结果

System.out.println(thCols); // prints 1
System.out.println(tdCols); // prints 2 - whereas I am expecting 3

为什么会发生这种情况?我做了我的搜索 - 但我能找到的最好的是关于 jSoup 如何期望正确构建的 HTML5 的 cmets。但是,上面的表格似乎是合规的,除非我错过了一些严重的东西。还有什么原因?

【问题讨论】:

  • ...&lt;td&gt;0.00&lt;/td&lt;/tr&gt; 似乎格式不正确。这是你的意图吗?
  • 哦 - 哎呀!这发生在缩短表格内容以更好地展示时。我已经编辑了文本。我还重新检查了源 - 表格 html 在那里正确形成,没有上述错字。感谢您的指针@luksch
  • 遵循此stackoverflow.com/questions/7985791/… 中包含的解决方案 - 但我不确定这是否是最佳方式。感谢您提供任何进一步的建议

标签: jsoup


【解决方案1】:

这是最新的 Jsoup 1.8.3 中的一个错误,在 Jsoup 1.8.2 版本中引入。如果您切换回 1.8.1,它应该可以按预期工作。另一种解决方案是为 tds 的数量创建一个选择器:

String htmlStr = ""
        +"<table class=\"xt\">"
        +"  <tbody>"
        +"   <tr><th class=\"bg-warning\" colspan=\"3\">-</th></tr>"
        +"   <tr><th class=\"bg-warning\">2014-08-29</th><td>0</td><td>0.00</td><td>0.00</td></tr>"
        +"  </tbody>"
        +"</table>";
Document doc = Jsoup.parse(htmlStr);
Element xt = doc.select("table.xt").first();
int thCols = xt.select("tr").eq(1).select("th").size();
int tdCols = xt.select("tr").eq(1).select("td").size();
int tdCols2 = xt.select("tr:eq(1)>td").size();

System.out.println(thCols); // prints 1
System.out.println(tdCols); // prints 2 - whereas I am expecting 3
System.out.println(tdCols2); // prints 3 as expected

这可能与here描述的错误相同

【讨论】:

  • 非常感谢@luksch - 降级到 1.8.1 解决了上述及相关问题(甚至遍历表也因索引问题而卡住)
猜你喜欢
  • 1970-01-01
  • 2016-11-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多