繁体   English   中英

jsoup不会删除元素

[英]jsoup does not delete elements

我又来了。

我得到了这段代码:

this.doc = Jsoup.parse(str);
        Elements tables = doc.getElementsByTag("table");
        if(tables!=null){
            for(Element table : tables){
                if(table != null){
                    Elements tds=table.getElementsByTag("td");
                    if(tds!=null){
                        for(Element td : tds){
                            String[] text=td.text().trim().split("\\s+");
                            if(text.length<2)td.remove();
                        }
                    }
                }
            }
        }
        Elements hs = doc.getElementsByTag("h1, h2, h3, h4");
        if(hs!=null)for(Element h : hs)if(h != null)h.remove();
        Elements blocks = doc.getElementsByTag("div, center, li, p, address, aside, audio, blockquote, canvas, dd, dl, fieldset, figcaption, figure, footer, form, header, hr, hgroup, li, ol, noscript, output, pre, section");
        if(blocks!=null){
            System.out.println(blocks.size());
            for(Element block : blocks){
                if(block != null){
                    String[] text=block.text().trim().split("\\s+");
                    if(text.length<2)block.remove();
                }
            }
        }
        Elements pdp = doc.getElementsByClass("pineDeletePoint");
        if(pdp!=null&&pdp.size()>0)pdp.remove();
        str = this.doc.outerHtml();

但是我仍然有块元素,其中我的html中少于两个词。

为什么我不能删除它们?

非常感谢您的帮助...

在您的代码中:

Elements hs = doc.getElementsByTag("h1, h2, h3, h4"); 

我知道您想要什么,但是传递多个标签,这些标签之间用分隔,不能与getElementsByTag() ,它可以与select()函数一起使用,例如doc.select("div, h1, h2") 但是我可以想到一个使用伪选择器 :matchesOwn(regex)的解决方案,其版本为^\\s*\\S+\\s*$ 这是一个简短的工作示例:

    String data = "<div>  asd asd</div><span><p>  asdd </p></span>";
    Document doc = Jsoup.parse(data);
    Elements elms = doc.select(":matchesOwn(^\\s*\\S+\\s*$)");
          // do whatever you are going to do with elms
    System.out.println(elms);  // print the elements having less than two words
    elms.remove(); // remove all elements from document which contains 
                   //  less than 2 words in their own text  
    System.out.println("\nprinting Document:\n"+doc);

并输出:

     <p> asdd </p>

printing Document:
<html>
 <head></head>
 <body>
  <div>
    asd asd
  </div>
  <span></span>
 </body>
</html>

暂无
暂无

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

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