要在BeautifulSoup中查找div名称的精确匹配,可以使用find_all()方法,并结合正则表达式来实现。
下面是一个示例代码:
from bs4 import BeautifulSoup
import re
html = """
Content 1
Content 2
Other
"""
soup = BeautifulSoup(html, 'html.parser')
# 使用正则表达式创建一个匹配规则
pattern = re.compile(r'^content$')
# 使用find_all()方法查找匹配规则的div元素
divs = soup.find_all('div', class_=pattern)
# 输出匹配到的div元素的文本内容
for div in divs:
print(div.text)
输出结果:
Content 1
Content 2
在上述代码中,我们首先创建了一个BeautifulSoup对象,然后使用正则表达式模式^content$
匹配div元素的class属性值为"content"的精确匹配。然后使用find_all()方法查找匹配规则的div元素,并通过for循环输出匹配到的div元素的文本内容。