【问题标题】:JSoup - Select all commentsJSoup - 选择所有评论
【发布时间】:2011-05-03 01:44:09
【问题描述】:

我想使用 JSoup 从文档中选择所有 cmets。我想做这样的事情:

for(Element e : doc.select("comment")) {
   System.out.println(e);
}

我试过这个:

for (Element e : doc.getAllElements()) {
  if (e instanceof Comment) {

  }

}

但是eclipse中出现以下错误“不兼容的条件操作数类型元素和注释”。

干杯,

皮特

【问题讨论】:

    标签: java screen-scraping extract comments jsoup


    【解决方案1】:

    由于Comment extends Node 您需要将instanceof 应用于节点对象,而不是元素,如下所示:

        for(Element e : doc.getAllElements()){
            for(Node n: e.childNodes()){
                if(n instanceof Comment){
                    System.out.println(n);
                }
            }
        }
    

    【讨论】:

      【解决方案2】:

      Kotlin 中,您可以通过Jsoup 获取整个Comment 中的每个Document 或特定Element,其中:

      fun Element.getAllComments(): List<Comment> {
        return this.allElements.flatMap { element ->
          element.childNodes().filterIsInstance<Comment>()
        }
      }
      

      【讨论】:

        猜你喜欢
        • 2015-03-04
        • 2015-04-17
        • 1970-01-01
        • 1970-01-01
        • 2014-07-06
        • 2016-12-15
        • 1970-01-01
        • 2021-02-20
        • 1970-01-01
        相关资源
        最近更新 更多