【发布时间】:2021-02-20 00:58:00
【问题描述】:
<div class="A B">123</div>
<div class="B">456</div>
要找到没有A类的div,如何排除?
【问题讨论】:
-
你的类名是否包含空格?
<div class="A B">123</div>
<div class="B">456</div>
要找到没有A类的div,如何排除?
【问题讨论】:
由于您的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>]
【讨论】: