【问题标题】:python: beautifulsoup find tag by class excluding some classpython:beautifulsoup 按类查找标签,不包括某些类
【发布时间】:2021-02-20 00:58:00
【问题描述】:
<div class="A B">123</div>
<div class="B">456</div>

要找到没有A类的div,如何排除?

【问题讨论】:

  • 你的类名是否包含空格?

标签: python-3.x beautifulsoup


【解决方案1】:

由于您的class name 包含空格,因此您不能在find_all 中使用lambda 函数。相反,您可以找到所有divs,并将其类名中不包含A 的所有divs 添加到list。以下是你的做法:

tags = soup.find_all('div')
tags = [tag for tag in tags if 'A' not in ''.join(tag['class'])]

完整代码:

from bs4 import BeautifulSoup

html = """
<div class="A B">123</div>
<div class="B">456</div>
"""

soup = BeautifulSoup(html,'html5lib')

tags = soup.find_all('div')
tags = [tag for tag in tags if 'A' not in ''.join(tag['class'])]

print(tags)

输出:

[<div class="B">456</div>]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-18
    • 2014-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多