Beautiful Soup 是一个 Python 的库,用于从 HTML 和 XML 文件中提取数据。它提供了很多简单的、Python 式的函数用来处理导航、搜索、修改分析树等功能。它是一个工具箱,通过解析文档为用户提供需要抓取的数据,因为简单,所以不需要多少代码就可以写出一个完整的应用程序。
Beautiful Soup 自动将输入文档转换为 Unicode 编码,输出文档转换为 UTF-8 编码。你不需要考虑编码方式,除非文档没有指定一个编码方式,这时,Beautiful Soup 就不能自动识别编码方式了。然后,它基于解析器(如 lxml 和 html5lib)来解析文档,并创建一个解析树,使开发者可以通过解析树轻松地提取所需的数据。
Beautiful Soup 支持多种解析器,包括:
以下是一个使用 Beautiful Soup 提取 <span>
标签内容的简单示例:
from bs4 import BeautifulSoup
html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
<span class="note">This is a note.</span>
"""
soup = BeautifulSoup(html_doc, 'html.parser')
# 查找所有的 <span> 标签
spans = soup.find_all('span')
for span in spans:
print(span.text) # 输出: This is a note.
<span>
标签原因:可能是由于标签的属性值与预期不符,或者标签嵌套在其他元素中。
解决方法:使用更具体的选择器,例如结合 class
或 id
属性进行查找。
specific_span = soup.find('span', class_='note')
print(specific_span.text)
原因:可能是由于输入文档的编码问题或解析器选择不当。
解决方法:确保文档编码正确,并尝试更换解析器。
soup = BeautifulSoup(html_doc, 'lxml') # 尝试使用 lxml 解析器
通过以上方法,你可以有效地使用 Beautiful Soup 来处理和分析 HTML/XML 文档中的 <span>
标签及其他元素。
领取专属 10元无门槛券
手把手带您无忧上云