要使用BeautifulSoup在属性中查找文本,可以使用find_all()方法,并传入一个字典作为参数,字典的键值对表示要查找的属性和对应的文本。
以下是一个示例代码:
from bs4 import BeautifulSoup
html = '''
BeautifulSoup Example
Hello, world!
This is a sample text.
Another sample text.
'''
soup = BeautifulSoup(html, 'html.parser')
# 在属性class为content的元素中查找文本为"Another sample text."
result = soup.find_all(attrs={'class': 'content'}, text="Another sample text.")
for element in result:
print(element.text)
输出结果:
Another sample text.
在上述代码中,我们首先创建了一个BeautifulSoup对象,然后使用find_all()方法来查找属性class为content且文本为"Another sample text."的元素。最后,使用循环打印出找到的元素的文本内容。
需要注意的是,在使用find_all()方法时,如果要查找多个属性,可以在字典中添加多个键值对。如果要查找的属性值包含多个类名,可以使用字符串列表的形式,如{'class': ['class1', 'class2']}
。