如何使用Jsoup搜索评论(“”)?

我想从源HTML中删除这些标签及其内容。

在搜索时,您基本上使用Elements.select(selector) ,其中selector 由此API定义。 但是注释在技术上不是元素,因此您可能会在这里感到困惑,它们仍然是由节点名称#comment标识的节点。

让我们看看它是如何工作的:

 import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Node; public class RemoveComments { public static void main(String... args) { String h = "" + "

bar

"; Document doc = Jsoup.parse(h); removeComments(doc); doc.html(System.out); } private static void removeComments(Node node) { for (int i = 0; i < node.childNodesSize();) { Node child = node.childNode(i); if (child.nodeName().equals("#comment")) child.remove(); else { removeComments(child); i++; } } } }

使用JSoup 1.11+(可能是旧版本),您可以应用filter:

 private void removeComments(Element article) { article.filter(new NodeFilter() { @Override public FilterResult tail(Node node, int depth) { if (node instanceof Comment) { return FilterResult.REMOVE; } return FilterResult.CONTINUE; } @Override public FilterResult head(Node node, int depth) { if (node instanceof Comment) { return FilterResult.REMOVE; } return FilterResult.CONTINUE; } }); } 

这很好,这个代码工作

 doc.select("#comment").remove(); 

并通过代码删除许多标签

 doc.select("script, style, meta, link, comment, CDATA, #comment").remove();