用BeautifulSoup解析XML需指定lxml-xml或xml解析器,不可用html.parser;推荐lxml因容错好,内置xml无需安装但易报错;注意编码匹配与命名空间限制。
用 BeautifulSoup 解析 XML 和解析 HTML 类似,但关键在于指定正确的解析器——必须用支持 XML 的解析器,比如 lxml 或 xml(Python 内置的 xml.etree.ElementTree 封装),不能用默认的 html.parser(它只处理 HTML)。
BeautifulSoup 本身不自带 XML 解析能力,需配合外部解析器:
pip install lxml
"xml" 作为解析器名假设有如下 XML 字符串:
代码解析方式:
from bs4 import BeautifulSoupxml_str = '''
''' 苹果 5.2 香蕉 3.8 soup = BeautifulSoup(xml_str, "lxml-xml") # 注意:用 "lxml-xml" 而非 "lxml"
或者用内置解析器:soup = BeautifulSoup(xml_str, "xml")
for item in soup.find_all("item"): name = item.find("name").text price = float(item.find("price").text) item_id = item.get("id") print(f"ID: {item_id}, 名称: {name}, 价格: {price}")
"lxml-xml",不是 "lxml"(后者按 HTML 模式解析,会忽略 XML 声明和命名空间),读文件时需用对应编码打开,再传给 BeautifulSoup;直接传字符串则确保是 Unicode(如 Python3 中的 str)lxml.etree 原生接口推荐做法:
with open("data.xml", "r", encoding="utf-8") as f:
soup = BeautifulSoup(f, "lxml-xml")
或者更稳妥地先读内容再解析(尤其编码不确定时)
with open("data.xml", "rb") as f: # 二进制模式读
soup = BeautifulSoup(f, "lxml-xml") # lxml-xml 可自动探测编码
基本上就这些。只要选对解析器、注意编码和命名空间限制,用 BeautifulSoup 解析常规 XML 很顺手。