【问题标题】:Extracting text with jsoup out of a table with breaks使用 jsoup 从带有中断的表中提取文本
【发布时间】:2014-05-02 09:11:17
【问题描述】:

有人知道我如何使用 Jsoup 提取这些文本吗?

<TR> 
    <TD bgColor=#ffa55c><B> 
      The first text I want.      </B><BR>
      <BR>
      The second text I want      <BR>
    </TD>
</TR>

我可以得到第一个:

Element element = doc.select("tr td:eq(1) b").get(1);
element.text();

但我没有得到第二个:(

【问题讨论】:

  • 什么是 .get(1),我没有看到 Element 类型有任何方法,例如 get() (jsoup.org/apidocs)?

标签: java android html parsing jsoup


【解决方案1】:

您需要关闭表格单元格标记TD 以使 HTML 格式正确

<table>
<TR> 
    <TD bgColor=#ffa55c><B> 
      The first text I want.      </B><BR>
      <BR>
      </TD><TD> <!-- add this -->
      The second text I want      <BR>
    </TD>
</TR>
</table>

否则JSoup会将第一个和第二个单元格视为一个,get会抛出一个IndexOutOfBoundsException,那么你可以简单使用

Element element = doc.select("td").get(2);

【讨论】:

  • 我同意,但不幸的是我无法更改 html 代码:/ 我需要处理这个丑陋的东西 <.>
【解决方案2】:

使用您提供给我们的表格数据,您可以一举轻松获取所有文本:

String html = "<TR><TD bgColor=#ffa55c><B>The first text I want.</B><BR><BR>The second text I want<BR></TD></TR>";

Document doc = Jsoup.parse(html);

System.out.println("test: " + doc.text());

输出:

test: The first text I want. The second text I want

我认为您需要将您的选择限制为 TR 并忽略它之后的所有内容,因此将其设为类似

// get the TRs
Elements elements = doc.select("tr");

// iterate through the TRs
for (Element element: elements){
    System.out.println(element.text());    
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多