lxml

Parsing

Análisis XML y HTML

Descripción general lxml

lxml es la biblioteca Python con más funciones para procesar XML y HTML. Combina lo mejor de libxml2 y libxslt con una API Pythonic, ofreciendo un análisis extremadamente rápido, compatibilidad total con XPath 1.0, transformaciones XSLT y manejo confiable incluso de documentos con formato incorrecto.

PyRunincluye lxml a través de la distribución del paquetePyodide. Puede analizar cadenas XML, ejecutar consultas XPath y navegar por árboles de documentos completamente en su navegador; no se requiere instalación local de libxml2 ni de ninguna otra biblioteca C.

Código y salida de ejecución

Analice XML y ejecute consultas XPath.

lxml XML ParserEjecutar en el editor
from lxml import etree

xml_data = """
<bookstore>
  <book category="science">
    <title>A Brief History of Time</title>
    <author>Stephen Hawking</author>
    <price>12.99</price>
  </book>
  <book category="fiction">
    <title>1984</title>
    <author>George Orwell</author>
    <price>9.99</price>
  </book>
</bookstore>
"""

root = etree.fromstring(xml_data.strip())

print("All books:")
for book in root.findall("book"):
    title  = book.find("title").text
    author = book.find("author").text
    price  = float(book.find("price").text)
    print(f"  {title} by {author} — ${price:.2f}")

expensive = root.xpath("//book[price > 10]/title/text()")
print("\nBooks over $10:", expensive)

Paquetes relacionados

Recursos recomendados de Python

Amplíe sus conocimientos con tutoriales interactivos relacionados, hojas de trucos y comparaciones de códigos.