Jsoup Element.hasText returns 对

Jsoup Element.hasText returns true for  

jsoup 的 Element.hasText 方法的文档说:

Test if this element has any text content (that is not just whitespace).

但下面的例子另有说明:

    String html1 = "<html><!-- no text here --></html>";
    String html2 = "<html><!-- this is text -->&nbsp;</html>";

    System.out.println(Jsoup.parse(html1).hasText());
    System.out.println(Jsoup.parse(html2).hasText());

输出为

false
true 

我希望

false 
false

有没有办法让 Jsoup 将 &nbsp; 视为空格?

不,你不能。 Jsoup 使用 Character.isWhitespace() 来确定文本是否包含除 whitespaces 之外的内容。此行为无法更改(配置)。 Character.isWhitespace() Javadoc 说:

A character is a Java whitespace character if and only if it satisfies one of the following criteria:

  • It is a Unicode space character (SPACE_SEPARATOR, LINE_SEPARATOR, or PARAGRAPH_SEPARATOR) but is not also a non-breaking space ('\u00A0', '\u2007', '\u202F').

所以你是一个人。

你可以做某事。喜欢

org.jsoup.helper.StringUtil.isBlank(element.ownText().replaceAll("\u00A0", ""));

StringUtil.isBlank(String)Element.hasText() 中使用,所以你将有相同的行为,但所有不可破坏的 space 字符将被删除。