在使用BeautifulSoup的findAll函数时,可以通过添加一个函数作为参数,自定义过滤条件来避免将包含
的元素视为不同的元素。以下是一个示例代码:
from bs4 import BeautifulSoup
# 示例HTML代码
html = """
This is a paragraph.
This is another paragraph.
This is a paragraph with
line break.
"""
# 自定义过滤函数
def custom_filter(tag):
if tag.name == "br":
return False
return True
# 使用findAll函数并传入自定义过滤函数作为参数
soup = BeautifulSoup(html, "html.parser")
paragraphs = soup.findAll(custom_filter, "p")
# 输出结果
for p in paragraphs:
print(p.getText())
输出结果为:
This is a paragraph.
This is another paragraph.
This is a paragraph with line break.
在这个示例中,自定义的过滤函数custom_filter
将会过滤掉所有的
标签,从而避免将包含
的元素视为不同的元素。