-
Overview
The
lxml
XML toolkit is a Pythonic binding for the C librarieslibxml2
andlibxslt
. It is unique in that it combines the speed and XML feature completeness of these libraries with the simplicity of a native Python API, mostly compatible but superior to the well-known ElementTree API. The latest release works with all CPython versions from 2.7 to 3.9. -
Tutorial
- the lxml.etree tutorial for XML processing
- John Shipman’s tutorial on Python XML processing with lxml
- Fredrik Lundh’s tutorial for ElementTree
pip install lxml from lxml import etree root = etree.Element("root") root.append(etree.Element("child1")) child2 = etree.SubElement(root, "child2") chile3 = etree.SubElement(root, "child3") # Elements are lists child = root[0] root[0].getparent() etree.tostring(root) # Elements carry attributes as a dict root1 = etree.Element("root", interesting="totally") root1.get("interesting") root1.set("hello","Huhu") etree.tostring(root) root1.keys()# display all the attributes root1.attrib # return a dict # Elements contain text root2 = etree.Element("root") root2.text = "TEXT" etree.tostring(root2,with_tail=False,method="text") ####### Using XPath to find text html.xpath("string()") html.xpath("//text()")
理解lxml module in Python
最新推荐文章于 2024-07-12 23:25:26 发布