BeautifulSoup在findAll中排除标签

问题描述

在beautifulsoup中,如何在使用findAll时排除特定标签内的标签。

让我们考虑这个示例,我想在html中找到<p>标记内的

标记之外的所有<tr>标记。

soup.findAll(['p'])

上面的代码将获取所有<p>标签,但我需要删除<p>标签内的<tr>标签。

解决方法

如果我理解正确,那么您想选择所有级别中没有p作为父项的所有tr

您可以选择所有p,然后使用findParent函数过滤结果。 findParent将返回给定标签名称的第一个父级,否则返回None

from bs4 import BeautifulSoup

html = """
  <tr>
    <p>1</p>
  </tr>
  
  <tr>
    <td>
      <p>2</p>
    </td>
  </tr>
  
  <p>3</p>
  
  <div>
    <p>4</p>
  </div>
"""

soup = BeautifulSoup(html,"html.parser")
print([p for p in soup.findAll('p') if not p.findParent('tr')])
,

您可以使用.select。示例:
选择所有<p>标签,但在<p>标签内排除<tr>标签。

soup.select('p:not(tr > p)')

选择所有<p>标签,但排除属于<p>标签子元素的<tr>标签

soup.select('p:not(tr p)')

选择所有<p><h2>标签,但排除<p>标签的子标签<tr>

soup.select('p,h2:not(tr p)')

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...