首先,需要将要解析的HTML文档传入BeautifulSoup对象中进行处理。
接着,使用find或find_all方法找到所需要的标签及其属性。
若找到了目标标签,则可以获取它的文本内容。
示例代码:
from bs4 import BeautifulSoup
html_doc = """
Example page
Example heading
Example paragraph.
Example content
"""
soup = BeautifulSoup(html_doc, 'html.parser')
# 找到class为content的span标签
span = soup.find('span', {'class': 'content'})
# 获取该标签的文本内容
content = span.get_text()
print(content) # 输出:Example content
在以上示例代码中,我们首先将HTML文档传入BeautifulSoup对象中,然后使用find方法找到class为content的span标签并获取它的文本内容。