如何使用 jsoup 选择 html 文档的叶标签

How to select leaf tags of an html document using jsoup

本文关键字:叶标签 标签 文档 何使用 jsoup 选择 html      更新时间:2023-09-26

我正在使用jsoup来解析html文档。我需要提取所有子div 元素。这基本上是没有嵌套div 标签的div 标签。我在java中使用了以下内容来提取div标签,

Elements bodyTag = document.select("div:not(div>div)"); 

下面是一个示例:

<div id="header">
     <div class="container">
         <div id="header-logo"> 
         <a href="/" title="mekay.com">
             <div id="logo">
             </div> </a>
        </div>
        <div id="header-banner">
            <div data-type="ad" data-publisher="lqm.j2ee.site" data-zone="ron">
            </div>
        </div>
     </div>
</div>

我只需要提取以下内容:

 <div id="logo">
 </div>
 <div data-type="ad" data-publisher="lqm.j2ee.site" data-zone="ron">
 </div>

相反,上面的代码片段返回所有div 标记。所以,你能帮我弄清楚这个选择器有什么问题吗

这个完美地工作

Elements innerMostDivs = doc.select("div:not(:has(div))");

在线试用

  • 添加您的 HTML 文件
  • 添加 CSS 查询作为div:not(:has(div))
  • 检查结果元素

如果您只想要没有任何子级的叶子div请使用这个

Elements emptyDivs = document.select("div:empty");

您现在使用的选择器表示 fetch me all the divs that are not direct children of another div .它带来第一个父级div是正常的,因为div id="header"不是div的直系子级。它的父级很可能是body.