删除所有 div,除了 jsoup 中所选 id 元素的第一个 div



要求是保留标题 - head1 和 head2 以及标题head1 和 head2 id 之后的第一个div 元素,并删除所有其他标题和div 元素。 请查看预期的输出可以使您清楚地了解我的要求。

输入网页:

<html>
<head> ...</head>
<body> 
<div id="main-content">
<div class ="abc">sample data </div>
<h1 id="head1">Example 1 </h1>
<div class="abc"> 
<table> <tr><td> table data 1</td></tr></table>
</div>
<div class="abc"> extra div </div>
<div class="abc"> one more extra div </div>
<h1 id="head2">Example 2</h1>
<div class="abc"> 
<table> 
<tr><td> table data 2</td></tr>
</table>
</div>
<div class="abc">extra div </div>
<div class="abc">one more extra div </div>
<h1 id="head3">Example 3</h1>
<div class="abc"> an extra div</div>
<div class="abc"> one more extra div </div>
<h1 id="head4"> Example 4</h1>
<div class="abc"> an extra div </div>
<div class="abc">an one more extra div </div>
</div>
</body>
</html>

下面是我的代码:

Elements contElements = document.select("main-content");
for(Element e :  contElements) {
if(e.tagName().equals("h1") &&     (!e.attr("id").equals("head1") &&    !e.attr("id").equals("head2")){
//remove h1 element with other id and all  div's after this h1 element
document.select("h1 ~ div ");
e.remove();
}
else {
//keep h1 element and the first div comes after h1 and   remove all other divs comes after this h1
document.select("h1 ~ div");
}

但是上面的代码片段没有按预期工作。实现预期输出还缺少什么。?

我的预期输出:

<html>
<head>  </head>
<body>
<div ID="main-content">
<div class="abc"> sample data </div>
<h1 id="head1">Example 1</h1>
<div class="abc"> 
<table> <tr><td> table data</td></tr></table>
</div>
<h1 id="head2">Example 2 </h1>
<div class="abc"> 
<table> <tr><td> table data</td></tr></table>
</div>
</div>
</body>
</html>

您可以使用 css 选择器而不是显式循环。

选择并删除id#head1#head2的所有h1元素:

document.select("#main-content h1:not(#head1):not(#head2)").remove();

选择并删除所有前面没有h1div元素:

document.select("#main-content div:not(h1 + div)").remove();

如果您只想对#main-content的直系后代进行操作,请将其放在>之后。

最新更新