繁体   English   中英

如何用Jsoup选择只有空格的元素?

[英]How to select elements with only whitespace with Jsoup?

我在选择只有空格的元素时遇到了问题。

鉴于html: <html><body><p> </p></body></html>

使用:empty不会选择我假设的p,因为其中有一个“”的文本节点

但是, :matchesOwn(^\\\\s+$)也不会选择它,因为似乎JSoup在对照正则表达式模式测试之前对文本执行了trim()

:matchesOwn(^$)将选择它,但也选择没有非空文本节点的元素

也许我错过了什么?

:matchesOwn根本不应该修剪,因为它使用正则表达式,应该评估整个文本

CSS选择器只能匹配特定类型的节点: element 选择器无法找到注释或文本节点。 为了找到只有空格的元素,我们必须依赖Jsoup API。

我们将查找仅具有一个唯一文本节点子节点的节点。 此唯一文本节点必须与以下正则表达式匹配^\\s+$ 为了得到(未修剪的)文本,我们将调用TextNode#getWholeText方法。

这是怎么做的:

String html = "<html><body><div><p> </p><p> </p><span>\n\t\n   </span></div><span></span></body></html>";

Document doc = Jsoup.parse(html);

final Matcher onlyWhitespaceMatcher = Pattern.compile("^\\s+$").matcher("");
new NodeTraversor(new NodeVisitor() {

    @Override
    public void head(Node node, int depth) {
        List<Node> childNodes = node.childNodes();
        // * We're looking for nodes with one child only otherwise we move on
        if (childNodes.size() != 1) {
            return;
        }

        // * This unique child node must be a TextNode
        Node uniqueChildNode = childNodes.get(0);
        if (uniqueChildNode instanceof TextNode == false) {
            return;
        }

        // * This unique TextNode must be whitespace only
        if (onlyWhitespaceMatcher.reset(((TextNode) uniqueChildNode).getWholeText()).matches()) {
            System.out.println(node.nodeName());
        }
    }

    @Override
    public void tail(Node node, int depth) {
        // void
    }
}).traverse(doc);
// Instead of traversing the whole document,
// we could narrow down the search to its body only with doc.body()

OUTPUT

p
p
span

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM