删除多余的 beautifulsoup html 标签

Remove redundant beautifulsoup html tags

如何删除 beautifulsoup 对象中的“冗余”html 标签?

为例
<html>
 <body>
  <div>
   <div>
    <div>
     <div>
      <div>
       <div>
        Close
       </div>
      </div>
     </div>
    </div>
   </div>
   <div>
    <div>
     <div style="width:80px">
      <div>
      </div>
      <div>
       <button>
        Close
       </button>
      </div>
     </div>
    </div>
   </div>
  </div>
  <div>
  </div>
 </body>
</html>

如何删除冗余 <div> 标签(冗余,因为它们只增加深度,但不包含任何附加信息或属性)到以下结构:

<html>
 <body>
       <div>
        Close
       </div>
     <div style="width:80px">
       <button>
        Close
       </button>
     </div>
 </body>
</html>

就图形算法而言,我试图将 beautifulsoup 树中不包含字符串和属性的多个节点合并在一起。

您可以使用 unwrap() 将任何没有属性(即 div.attrs == {})的 div 替换为它们的 children:

for div in soup.find_all('div'):
    if not div.attrs:
        div.unwrap()

print(soup.prettify()) 的输出:

<html>
 <body>
  <button>
   Close
  </button>
  <div style="width:80px">
   <button>
    Close
   </button>
  </div>
 </body>
</html>

对于更新的示例(见评论),它将是:

for div in soup.find_all('div'):
    if not div.attrs and div.div:
        div.unwrap()

即如果 div 没有属性并且其后跟另一个 div

,则将其移除

我刚刚创建了一个似乎可以完成这项工作的代码片段:

        for x in reversed(soup()):
            if not x.string and not x.attrs and len(x.findChildren(recursive=False)) <= 1:
                x.unwrap()

reversed 是必需的,否则空标签将被视为兄弟标签,阻止展开。