使用BeautifulSoup的.find_all()方法可以根据多个条件进行筛选。下面是一个示例代码:
from bs4 import BeautifulSoup
html = """
这是一个段落
这是另一个段落
这是第三个段落
"""
soup = BeautifulSoup(html, 'html.parser')
#使用.find_all()方法筛选同时满足文本=True和IMG Alt=True的元素
elements = soup.find_all(lambda tag: tag.name == 'p' and tag.text and tag.find_previous('img') and tag.find_previous('img')['alt'])
#打印筛选结果
for element in elements:
print(element.text)
运行结果:
这是一个段落
这是另一个段落
在上面的示例中,我们使用了lambda函数作为.find_all()方法的参数,通过多个条件进行筛选。其中,lambda函数中的条件为tag.name == 'p' and tag.text and tag.find_previous('img') and tag.find_previous('img')['alt']
,即筛选出标签名为'p'、有文本内容、前面有img标签、img标签的alt属性不为空的元素。最后,我们遍历筛选结果并打印出文本内容。