【问题标题】:How to remove part of the webpage in Jsoup?如何在 Jsoup 中删除部分网页?
【发布时间】:2012-04-13 02:20:57
【问题描述】:

我目前正在研究 Jsoup。我已经得到了一个元素 content 看起来像

<p>123</p>
<p>456</p>
<p>789</p>
<p>abc</p>
<p>efg</p>
....

efg 行之后有几行,但我希望删除 efg 行之后的所有行,我希望结果是一个元素(不是元素)

我尝试了几种方法,例如

content.children().removeAll(content.getElementsByIndexGreaterThan(content.children().indexOf(content.select("p:contains(efg)"))));

content.getElementsByIndexGreaterThan(content.select("p:contains(efg)")).remove();

不幸的是,它们都不起作用。有没有人对此有更好的解决方案?感谢您阅读这篇文章。

【问题讨论】:

    标签: java android jsoup


    【解决方案1】:
    <div> 
     <p>123</p> 
     <p>456</p> 
     <p>789</p> 
     <p>abc</p> 
     <p>efg</p> 
     <p>111</p> 
     <p>222</p> 
     <p>333</p> 
     <p>444</p> 
    </div>
    

    public static void main(String[] args) throws Exception {
        String html = new String(Files.readAllBytes(Paths.get("input.html")));
        Document doc = Jsoup.parse(html);
        Element content = doc.select("div").first();
    
        Element lastValidElement = content.select("p:contains(efg)").first();
        int lastValidElementIndex = content.children().indexOf(lastValidElement);
        content.getElementsByIndexGreaterThan(lastValidElementIndex).remove();
        System.out.println(content);
    }
    

    <div> 
     <p>123</p> 
     <p>456</p> 
     <p>789</p> 
     <p>abc</p> 
     <p>efg</p>     
    </div>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多