繁体   English   中英

如何在Jsoup中删除部分网页?

[英]How to remove part of the webpage in Jsoup?

我目前正在研究Jsoup。 我已经收到一个Element content看起来像

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

efg行之后有几行,但是我希望删除efg行之后的所有行,并且我希望结果是一个Element(不是Elements)

我尝试了几种方法,例如

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

要么

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

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

<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>

暂无
暂无

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

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