47

假设我有一个这样的 html 片段:

<p> <span> foo </span> <em> bar <a> foobar </a> baz </em> </p>

我想从中提取的是:

foo bar foobar baz

所以我的问题是:我怎样才能从 html 中剥离所有包装标签,并只获取与 html 中相同顺序的文本?正如您在标题中看到的,我想使用 jsoup 进行解析。

重音 html 示例(注意 'á' 字符):

<p><strong>Tarthatatlan biztonsági viszonyok</strong></p>
<p><strong>Tarthatatlan biztonsági viszonyok</strong></p>

我想要的是:

Tarthatatlan biztonsági viszonyok
Tarthatatlan biztonsági viszonyok

这个 html 不是静态的,通常我只想要一个通用 html 片段的每个文本都以解码的人类可读形式,宽度换行符。

4

3 回答 3

64

使用 Jsoup:

final String html = "<p> <span> foo </span> <em> bar <a> foobar </a> baz </em> </p>";
Document doc = Jsoup.parse(html);

System.out.println(doc.text());

输出:

foo bar foobar baz

如果您只想要 p-tag 的文本,请使用它而不是doc.text()

doc.select("p").text();

...或只有身体:

doc.body().text();

越线:

final String html = "<p><strong>Tarthatatlan biztonsági viszonyok</strong></p>"
        + "<p><strong>Tarthatatlan biztonsági viszonyok</strong></p>";
Document doc = Jsoup.parse(html);

for( Element element : doc.select("p") )
{
    System.out.println(element.text());
    // eg. you can use a StringBuilder and append lines here ...
}

输出:

Tarthatatlan biztonsági viszonyok  
Tarthatatlan biztonsági viszonyok
于 2012-10-17T21:38:06.427 回答
15

使用正则表达式: -

String str = "<p> <span> foo </span> <em> bar <a> foobar </a> baz </em> </p>";
str = str.replaceAll("<[^>]*>", "");
System.out.println(str);

输出: -

  foo   bar  foobar  baz 

使用 Jsoup:-

Document doc = Jsoup.parse(str); 
String text = doc.text();
于 2012-10-17T21:35:03.040 回答
7

Actually, the correct way to clean with Jsoup is through a Whitelist

...
final String html = "<p> <span> foo </span> <em> bar <a> foobar </a> baz </em> </p>";
Document doc = Jsoup.parse(html);
Whitelist wl = Whitelist.none()
String cleanText = Jsoup.clean(doc.html(), wl)

If you want to still preserve some tags:

Whitelist wl = new Whitelist().relaxed().removeTags("a")
于 2017-06-19T16:25:37.740 回答