如何使用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();
- 删除ThreadPoolExecutor的所有排队任务
- Java:游标当前位置的列号和行号
- 为什么在计算表达式时将byte和short值提升为int
- 使用JavaFX Platform.runLater并从不同的线程访问UI
- JCA示例实现
- 如何一次将数据写入两个java.io.OutputStream对象?
- SWIG(v1.3.29)生成的C ++到Java Vector类不能正常运行
- 什么时候用HttpServletRequest / Response之外的任何东西调用javax.servlet.Filter.doFilter(ServletRequest req,ServletResponse res)?
- 从Hibernate 3迁移到4会降低启动速度