lxml 和 ElementTree 有什么区别?

What are the differences between lxml and ElementTree?

说到generating XML data in Python, there are two libraries I often see recommended: lxml and ElementTree

据我所知,这两个库非常相似。它们似乎都有相似的模块名称、使用指南和功能。甚至导入语句也非常相似。

 # Importing lxml and ElementTree
import lxml.etree
import xml.etree.ElementTree

Python 的 lxmlElementTree 库有什么区别?

我不会说 lxml 在所有方面都比 ET 快,因为这两个模块都提供了大量的功能。为了提供一点上下文,ElementTree 还支持 XPath,但特别是 ET 有一个独特且有用的函数,称为 iterparse(),它将 XML 文档重新制作为可迭代的。这导致解析速度更快,特别是对于大型 XML 文件。

ET API 本身创建的元素类型是列表和字典的混合体。这可能会让那些刚接触该模块的人头疼,但坐下来使用它,您会发现它非常灵活。

ElementTree 内置了 Python 标准库,其中包括其他数据模块类型,例如 jsoncsv。这意味着该模块随 Python 的每个安装一起提供。对于大多数正常的 XML 操作,包括构建文档树和简单搜索和解析元素属性和节点值,甚至名称空间,ElementTree 是一个可靠的处理程序。

Lxml is a third-party module that requires installation. In many ways lxml actually extends ElementTree as most operations in the built-in module are available. Chief among this extension is that lxml supports both XPath 1.0 and XSLT 1.0. Additionally, lxml can parse HTML documents that are not XML compliant and hence is used for web-scraping operations and even as the parser in BeautifulSoup and engine in Pandas, pandas.read_html(). Other useful, common features of lxml include pretty_print output, objectify, and sax支持。当然,作为第三方模块,与标准库相比,具有附加功能的版本也很容易访问。