Python Lxml Example

P

The lxml.etree Tutorial

The lxml.etree Tutorial

Author:
Stefan Behnel
This is a tutorial on XML processing with It briefly
overviews the main concepts of the ElementTree API, and some simple
enhancements that make your life as a programmer easier.
For a complete reference of the API, see the generated API
documentation.
Contents
The Element class
Elements are lists
Elements carry attributes as a dict
Elements contain text
Using XPath to find text
Tree iteration
Serialisation
The ElementTree class
Parsing from strings and files
The fromstring() function
The XML() function
The parse() function
Parser objects
Incremental parsing
Event-driven parsing
Namespaces
The E-factory
ElementPath
A common way to import is as follows:
>>> from lxml import etree
If your code only uses the ElementTree API and does not rely on any
functionality that is specific to, you can also use (any part
of) the following import chain as a fall-back to the original ElementTree:
try:
from lxml import etree
print(“running with “)
except ImportError:
# Python 2. 5
import as etree
print(“running with cElementTree on Python 2. 5+”)
print(“running with ElementTree on Python 2. 5+”)
# normal cElementTree install
import cElementTree as etree
print(“running with cElementTree”)
# normal ElementTree install
import elementtree. ElementTree as etree
print(“running with ElementTree”)
print(“Failed to import ElementTree from any known place”)
To aid in writing portable code, this tutorial makes it clear in the examples
which part of the presented API is an extension of over the
original ElementTree API, as defined by Fredrik Lundh’s ElementTree
library.
An Element is the main container object for the ElementTree API. Most of
the XML tree functionality is accessed through this class. Elements are
easily created through the Element factory:
>>> root = etree. Element(“root”)
The XML tag name of elements is accessed through the tag property:
Elements are organised in an XML tree structure. To create child elements and
add them to a parent element, you can use the append() method:
>>> ( etree. Element(“child1”))
However, this is so common that there is a shorter and much more efficient way
to do this: the SubElement factory. It accepts the same arguments as the
Element factory, but additionally requires the parent as first argument:
>>> child2 = bElement(root, “child2”)
>>> child3 = bElement(root, “child3”)
To see that this is really XML, you can serialise the tree you have created:
>>> print(string(root, pretty_print=True))





To make the access to these subelements easy and straight forward,
elements mimic the behaviour of normal Python lists as closely as
possible:
>>> child = root[0]
>>> print()
child1
>>> print(len(root))
3
>>> (root[1]) # only!
1
>>> children = list(root)
>>> for child in root:… print()
child2
child3
>>> (0, etree. Element(“child0”))
>>> start = root[:1]
>>> end = root[-1:]
>>> print(start[0])
child0
>>> print(end[0])
Prior to ElementTree 1. 3 and lxml 2. 0, you could also check the truth value of
an Element to see if it has children, i. e. if the list of children is empty:
if root: # this no longer works!
print(“The root element has children”)
This is no longer supported as people tend to expect that a “something”
evaluates to True and expect Elements to be “something”, may they have
children or not. So, many users find it surprising that any Element
would evaluate to False in an if-statement like the above. Instead,
use len(element), which is both more explicit and less error prone.
>>> print(element(root)) # test if it’s some kind of Element
True
>>> if len(root): # test if it has children… print(“The root element has children”)
The root element has children
There is another important case where the behaviour of Elements in lxml
(in 2. 0 and later) deviates from that of lists and from that of the
original ElementTree (prior to version 1. 3 or Python 2. 7/3. 2):
>>> root[0] = root[-1] # this moves the element in!
In this example, the last element is moved to a different position,
instead of being copied, i. it is automatically removed from its
previous position when it is put in a different place. In lists,
objects can appear in multiple positions at the same time, and the
above assignment would just copy the item reference into the first
position, so that both contain the exact same item:
>>> l = [0, 1, 2, 3]
>>> l[0] = l[-1]
>>> l
[3, 1, 2, 3]
Note that in the original ElementTree, a single Element object can sit
in any number of places in any number of trees, which allows for the same
copy operation as with lists. The obvious drawback is that modifications
to such an Element will apply to all places where it appears in a tree,
which may or may not be intended.
The upside of this difference is that an Element in always
has exactly one parent, which can be queried through the getparent()
method. This is not supported in the original ElementTree.
>>> root is root[0]. getparent() # only!
If you want to copy an element to a different position in,
consider creating an independent deep copy using the copy module
from Python’s standard library:
>>> from copy import deepcopy
>>> element = etree. Element(“neu”)
>>> ( deepcopy(root[1]))
>>> print(element[0])
>>> print([ for c in root])
[‘child3’, ‘child1’, ‘child2′]
The siblings (or neighbours) of an element are accessed as next and previous
elements:
>>> root[0] is root[1]. getprevious() # only!
>>> root[1] is root[0]. getnext() # only!
XML elements support attributes. You can create them directly in the Element
factory:
>>> root = etree. Element(“root”, interesting=”totally”)
>>> string(root)
b’
Attributes are just unordered name-value pairs, so a very convenient way
of dealing with them is through the dictionary-like interface of Elements:
>>> print((“interesting”))
totally
>>> print((“hello”))
None
>>> (“hello”, “Huhu”)
Huhu
b’
>>> sorted(())
[‘hello’, ‘interesting’]
>>> for name, value in sorted(()):… print(‘%s =%r’% (name, value))
hello = ‘Huhu’
interesting = ‘totally’
For the cases where you want to do item lookup or have other reasons for
getting a ‘real’ dictionary-like object, e. g. for passing it around,
you can use the attrib property:
>>> attributes =
>>> print(attributes[“interesting”])
>>> print((“no-such-attribute”))
>>> attributes[“hello”] = “Guten Tag”
>>> print(attributes[“hello”])
Guten Tag
Note that attrib is a dict-like object backed by the Element itself.
This means that any changes to the Element are reflected in attrib
and vice versa. It also means that the XML tree stays alive in memory
as long as the attrib of one of its Elements is in use. To get an
independent snapshot of the attributes that does not depend on the XML
tree, copy it into a dict:
>>> d = dict()
[(‘hello’, ‘Guten Tag’), (‘interesting’, ‘totally’)]
Elements can contain text:
>>> = “TEXT”
TEXT
b’TEXT
In many XML documents (data-centric documents), this is the only place where
text can be found. It is encapsulated by a leaf tag at the very bottom of the
tree hierarchy.
However, if XML is used for tagged text documents such as (X)HTML, text can
also appear between different elements, right in the middle of the tree:
Hello
World
Here, the
tag is surrounded by text. This is often referred to as
document-style or mixed-content XML. Elements support this through their
tail property. It contains the text that directly follows the element, up
to the next element in the XML tree:
>>> html = etree. Element(“html”)
>>> body = bElement(html, “body”)
>>> string(html)
b’TEXT‘
>>> br = bElement(body, “br”)
b’TEXT

>>> = “TAIL”
b’TEXT
TAIL‘
The two properties and are enough to represent any
text content in an XML document. This way, the ElementTree API does
not require any special text nodes in addition to the Element
class, that tend to get in the way fairly often (as you might know
from classic DOM APIs).
However, there are cases where the tail text also gets in the way.
For example, when you serialise an Element from within the tree, you
do not always want its tail text in the result (although you would
still want the tail text of its children). For this purpose, the
tostring() function accepts the keyword argument with_tail:
>>> string(br)
b’
TAIL’
>>> string(br, with_tail=False) # only!
b’

If you want to read only the text, i. without any intermediate
tags, you have to recursively concatenate all text and tail
attributes in the correct order. Again, the tostring() function
comes to the rescue, this time using the method keyword:
>>> string(html, method=”text”)
b’TEXTTAIL’
Another way to extract the text content of a tree is XPath, which
also allows you to extract the separate text chunks into a list:
>>> print((“string()”)) # only!
TEXTTAIL
>>> print((“//text()”)) # only!
[‘TEXT’, ‘TAIL’]
If you want to use this more often, you can wrap it in a function:
>>> build_text_list = (“//text()”) # only!
>>> print(build_text_list(html))
Note that a string result returned by XPath is a special ‘smart’
object that knows about its origins. You can ask it where it came
from through its getparent() method, just as you would with
Elements:
>>> texts = build_text_list(html)
>>> print(texts[0])
>>> parent = texts[0]. getparent()
body
>>> print(texts[1])
TAIL
>>> print(texts[1]. getparent())
br
You can also find out if it’s normal text content or tail text:
>>> print(texts[0]. is_text)
>>> print(texts[1]. is_text)
False
>>> print(texts[1]. is_tail)
While this works for the results of the text() function, lxml will
not tell you the origin of a string value that was constructed by the
XPath functions string() or concat():
>>> stringify = (“string()”)
>>> print(stringify(html))
>>> print(stringify(html). getparent())
For problems like the above, where you want to recursively traverse the tree
and do something with its elements, tree iteration is a very convenient
solution. Elements provide a tree iterator for this purpose. It yields
elements in document order, i. in the order their tags would appear if you
serialised the tree to XML:
>>> bElement(root, “child”) = “Child 1”
>>> bElement(root, “child”) = “Child 2”
>>> bElement(root, “another”) = “Child 3”
Child 1
Child 2
Child 3
>>> for element in ():… print(“%s -%s”% (, ))
root – None
child – Child 1
child – Child 2
another – Child 3
If you know you are only interested in a single tag, you can pass its name to
iter() to have it filter for you. Starting with lxml 3. 0, you can also
pass more than one tag to intercept on multiple tags during iteration.
>>> for element in (“child”):… print(“%s -%s”% (, ))
>>> for element in (“another”, “child”):… print(“%s -%s”% (, ))
By default, iteration yields all nodes in the tree, including
ProcessingInstructions, Comments and Entity instances. If you want to
make sure only Element objects are returned, you can pass the
Element factory as tag parameter:
>>> ((“#234”))
>>> (mment(“some comment”))
>>> for element in ():… if isinstance(, basestring): # or ‘str’ in Python 3… print(“%s -%s”% (, ))… else:… print(“SPECIAL:%s -%s”% (element, ))
SPECIAL: ê – ê
SPECIAL: – some comment
>>> for element in (tag=etree. Element):… print(“%s -%s”% (, ))
>>> for element in ():… print()
ê
Note that passing a wildcard “*” tag name will also yield all
Element nodes (and only elements).
In, elements provide further iterators for all directions in the
tree: children, parents (or rather ancestors) and siblings.
Serialisation commonly uses the tostring() function that returns a
string, or the () method that writes to a file, a
file-like object, or a URL (via FTP PUT or HTTP POST). Both calls accept
the same keyword arguments like pretty_print for formatted output
or encoding to select a specific output encoding other than plain
ASCII:
>>> root = (‘‘)
b’
>>> print(string(root, xml_declaration=True))


>>> print(string(root, encoding=’iso-8859-1′))




Note that pretty printing appends a newline at the end.
For more fine-grained control over the pretty-printing, you can add
whitespace indentation to the tree before serialising it, using the
indent() function (added in lxml 4. 5):
>>> root = (‘n‘)
>>> print(string(root))


>>> (root)
>>>
‘n ‘
>>> root[0]
>>> (root, space=” “)
>>> (root, space=”t”)
ntnttntn
In lxml 2. 0 and later (as well as ElementTree 1. 3), the serialisation
functions can do more than XML serialisation. You can serialise to
HTML or extract the text content by passing the method keyword:
>>> root = (… ‘

Hello
World

‘)
>>> string(root) # default: method = ‘xml’
b’

Hello
World


>>> string(root, method=’xml’) # same as above
>>> string(root, method=’html’)
b’

Hello
World


>>> print(string(root, method=’html’, pretty_print=True))


Hello
World



>>> string(root, method=’text’)
b’HelloWorld’
As for XML serialisation, the default encoding for plain text
serialisation is ASCII:
>>> br = next((‘br’)) # get first result of iteration
>>> = u’Wxf6rld’
>>> string(root, method=’text’) # doctest: +ELLIPSIS
Traceback (most recent call last):…
UnicodeEncodeError: ‘ascii’ codec can’t encode character u’xf6’…
>>> string(root, method=’text’, encoding=”UTF-8″)
b’HelloWxc3xb6rld’
Here, serialising to a Python unicode string instead of a byte string
might become handy. Just pass the name ‘unicode’ as encoding:
>>> string(root, encoding=’unicode’, method=’text’)
u’HelloWxf6rld’
The W3C has a good article about the Unicode character set and
character encodings.
An ElementTree is mainly a document wrapper around a tree with a
root node. It provides a couple of methods for serialisation and
general document handling.
>>> root = (”’… ]>… &tasty;… ”’)
>>> tree = etree. ElementTree(root)
>>> print(cinfo. xml_version)
1. 0
>>> print(ctype)

>>> lic_id = ‘-//W3C//DTD XHTML 1. 0 Transitional//EN’
>>> stem_url = ”

An ElementTree is also what you get back when you call the
parse() function to parse files or file-like objects (see the
parsing section below).
One of the important differences is that the ElementTree class
serialises as a complete document, as opposed to a single Element.
This includes top-level processing instructions and comments, as well
as a DOCTYPE and other DTD content in the document:
>>> print(string(tree)) # lxml 1. 3. 4 and later
]>
parsnips
In the original implementation and in lxml
up to 1. 3, the output looks the same as when serialising only
the root Element:
>>> print(string(troot()))
This serialisation behaviour has changed in lxml 1. 4. Before,
the tree was serialised without DTD content, which made lxml
lose DTD information in an input-output cycle.
supports parsing XML in a number of ways and from all
important sources, namely strings, files, URLs (/ftp) and
file-like objects. The main parse functions are fromstring() and
parse(), both called with the source as first argument. By
default, they use the standard parser, but you can always pass a
different parser as second argument.
The fromstring() function is the easiest way to parse a string:
>>> some_xml_data = “data
>>> root = omstring(some_xml_data)
root
b’data
The XML() function behaves like the fromstring() function, but is
commonly used to write XML literals right into the source:
>>> root = (“data“)
There is also a corresponding function HTML() for HTML literals.
>>> root = (“

data

“)
b’

data


The parse() function is used to parse from files and file-like objects.
As an example of such a file-like object, the following code uses the
BytesIO class for reading from a string instead of an external file.
That class comes from the io module in Python 2. 6 and later. In older
Python versions, you will have to use the StringIO class from the
StringIO module. However, in real life, you would obviously avoid
doing this all together and use the string parsing functions above.
>>> from io import BytesIO
>>> some_file_or_file_like_object = BytesIO(b”data“)
>>> tree = (some_file_or_file_like_object)
>>> string(tree)
Note that parse() returns an ElementTree object, not an Element object as
the string parser functions:
>>> root = troot()
The reasoning behind this difference is that parse() returns a
complete document from a file, while the string parsing functions are
commonly used to parse XML fragments.
The parse() function supports any of the following sources:
an open file object (make sure to open it in binary mode)
a file-like object that has a (byte_count) method returning
a byte string on each call
a filename string
an HTTP or FTP URL string
Note that passing a filename or URL is usually faster than passing an
open file or file-like object. However, the HTTP/FTP client in libxml2
is rather simple, so things like HTTP authentication require a dedicated
URL request library, e. urllib2 or requests. These libraries
usually provide a file-like object for the result that you can parse
from while the response is streaming in.
By default, uses a standard parser with a default setup. If
you want to configure the parser, you can create a new instance:
>>> parser = etree. XMLParser(remove_blank_text=True) # only!
This creates a parser that removes empty text between tags while parsing,
which can reduce the size of the tree and avoid dangling tail text if you know
that whitespace-only content is not meaningful for your data. An example:
>>> root = (“ “, parser)
b’

Note that the whitespace content inside the tag was not removed, as
content at leaf elements tends to be data content (even if blank). You can
easily remove it in an additional step by traversing the tree:
>>> for element in (“*”):… if is not None and not ():… = None
b’

See help(etree. XMLParser) to find out about the available parser options.
provides two ways for incremental step-by-step parsing. One is
through file-like objects, where it calls the read() method repeatedly.
This is best used where the data arrives from a source like urllib or any
other file-like object that can provide data on request. Note that the parser
will block and wait until data becomes available in this case:
>>> class DataSource:… data = [ b”<", b"a/", b"><", b"/root>“]… def read(self, requested_size):… try:… return (0)… except IndexError:… return b”
>>> tree = (DataSource())
b’

The second way is through a feed parser interface, given by the feed(data)
and close() methods:
>>> parser = etree. XMLParser()
>>> (“>> (“t><") >>> (“a/”)
>>> (“><") >>> (“/root>”)
>>> root = ()
Here, you can interrupt the parsing process at any time and continue it later
on with another call to the feed() method. This comes in handy if you
want to avoid blocking calls to the parser, e. in frameworks like Twisted,
or whenever data comes in slowly or in chunks and you want to do other things
while waiting for the next chunk.
After calling the close() method (or when an exception was raised
by the parser), you can reuse the parser by calling its feed()
method again:
>>> (““)
b’
Sometimes, all you need from a document is a small fraction somewhere deep
inside the tree, so parsing the whole tree into memory, traversing it and
dropping it can be too much overhead. supports this use case
with two event-driven parser interfaces, one that generates parser events
while building the tree (iterparse), and one that does not build the tree
at all, and instead calls feedback methods on a target object in a SAX-like
fashion.
Here is a simple iterparse() example:
>>> some_file_like = BytesIO(b”
data“)
>>> for event, element in erparse(some_file_like):… print(“%s, %4s, %s”% (event,, ))
end, a, data
end, root, None
By default, iterparse() only generates events when it is done parsing an
element, but you can control this through the events keyword argument:
>>> for event, element in erparse(some_file_like,… events=(“start”, “end”)):… print(“%5s, %4s, %s”% (event,, ))
start, root, None
start, a, data
Note that the text, tail, and children of an Element are not necessarily present
yet when receiving the start event. Only the end event guarantees
that the Element has been parsed completely.
It also allows you to () or modify the content of an Element to
save memory. So if you parse a large tree and you want to keep memory
usage small, you should clean up parts of the tree that you no longer
need. The keep_tail=True argument to () makes sure that
(tail) text content that follows the current element will not be touched.
It is highly discouraged to modify any content that the parser may not
have completely read through yet.
>>> some_file_like = BytesIO(… b”data“)
>>> for event, element in erparse(some_file_like):… if == ‘b’:… print()… elif == ‘a’:… print(“** cleaning up the subtree”)… (keep_tail=True)
data
** cleaning up the subtree
A very important use case for iterparse() is parsing large
generated XML files, e. database dumps. Most often, these XML
formats only have one main data item element that hangs directly below
the root node and that is repeated thousands of times. In this case,
it is best practice to let do the tree building and only to
intercept on exactly this one Element, using the normal tree API
for data extraction.
>>> xml_file = BytesIO(b”’… ABCabcMORE DATAmore dataXYZxyz… ”’)
>>> for _, element in erparse(xml_file, tag=’a’):… print(‘%s –%s’% (ndtext(‘b’), element[1]))… (keep_tail=True)
ABC — abc
MORE DATA — more data
XYZ — xyz
If, for some reason, building the tree is not desired at all, the
target parser interface of can be used. It creates
SAX-like events by calling the methods of a target object. By
implementing some or all of these methods, you can control which
events are generated:
>>> class ParserTarget:… events = []… close_count = 0… def start(self, tag, attrib):… ((“start”, tag, attrib))… def close(self):… events, =, []… ose_count += 1… return events
>>> parser_target = ParserTarget()
>>> parser = etree. XMLParser(target=parser_target)
>>> events = omstring(‘‘, parser)
>>> print(ose_count)
>>> for event in events:… print(‘event:%s – tag:%s’% (event[0], event[1]))… for attr, value in event[2]():… print(‘ *%s =%s’% (attr, value))
event: start – tag: root
* test = true
You can reuse the parser and its target as often as you like, so you
should take care that the () method really resets the
target to a usable state (also in the case of an error! ).
2
4
The ElementTree API avoids
namespace prefixes
wherever possible and deploys the real namespace (the URI) instead:
>>> xhtml = etree. Element(“{html”)
>>> body = bElement(xhtml, “{body”)
>>> = “Hello World”
>>> print(string(xhtml, pretty_print=True))
Hello World
>>> print((“bgcolor”))
>>> (XHTML + “bgcolor”)
‘#CCFFAA’
You can also use XPath with fully qualified names:
>>> find_xhtml_body = XPath( # lxml only!… “//{%s}body”% XHTML_NAMESPACE)
>>> results = find_xhtml_body(xhtml)
>>> print(results[0])
{body
For convenience, you can use “*” wildcards in all iterators of,
both for tag names and namespaces:
>>> for el in (‘*’): print() # any element
>>> for el in (‘{*’): print()
>>> for el in (‘{*}body’): print()
To look for elements that do not have a namespace, either use the
plain tag name or provide the empty namespace explicitly:
>>> [ for el in (‘{body’)]
[‘{body’]
>>> [ for el in (‘body’)]
[]
>>> [ for el in (‘{}body’)]
>>> [ for el in (‘{}*’)]
The E-factory provides a simple and compact syntax for generating XML and
HTML:
>>> from er import E
>>> def CLASS(*args): # class is a reserved word in Python… return {“class”:’ ‘(args)}
>>> html = page = (… ( # create an Element called “html”… (… (“This is a sample document”)… ),… E. h1(“Hello! “, CLASS(“title”)),… p(“This is a paragraph with “, E. b(“bold”), ” text in it! “),… p(“This is another paragraph, with a”, “n “,… a(“link”, href=”), “. “),… p(“Here are some reserved characters: . (“

And finally an embedded XHTML fragment.

“),… )… )
>>> print(string(page, pretty_print=True))

This is a sample document

Hello!

This is a paragraph with bold text in it!

This is another paragraph, with a
The dog and the hog The dog Once upon a time,… And then… The hog Sooner or later… One such example is the module, which provides a
vocabulary for HTML.
When dealing with multiple namespaces, it is good practice to define
one ElementMaker for each namespace URI. Again, note how the above
example predefines the tag builders in named constants. That makes it
easy to put all tag declarations of a namespace into one Python module
and to import/use the tag name constants from there. This avoids
pitfalls like typos or accidentally missing namespaces.
The ElementTree library comes with a simple XPath-like path language
called ElementPath. The main difference is that you can use the
{namespace}tag notation in ElementPath expressions. However,
advanced features like value comparison and functions are not
available.
In addition to a full XPath implementation, supports the
ElementPath language in the same way ElementTree does, even using
(almost) the same implementation. The API provides four methods here
that you can find on Elements and ElementTrees:
iterfind() iterates over all Elements that match the path
expression
findall() returns a list of matching Elements
find() efficiently returns only the first match
findtext() returns the content of the first match
Here are some examples:
>>> root = (“
aText“)
Find a child of an Element:
>>> print((“b”))
>>> print((“a”))
a
Find an Element anywhere in the tree:
>>> print((“. //b”))
b
>>> [ for b in erfind(“. //b”)]
[‘b’, ‘b’]
Find Elements with a certain attribute:
>>> print(ndall(“. //a[@x]”)[0])
>>> print(ndall(“. //a[@y]”))
In lxml 3. 4, there is a new helper to generate a structural ElementPath
expression for an Element:
>>> a = root[0]
>>> print(telementpath(a[0]))
a/b[1]
>>> print(telementpath(a[1]))
a/c
>>> print(telementpath(a[2]))
a/b[2]
>>> (telementpath(a[2])) == a[2]
As long as the tree is not modified, this path expression represents an
identifier for a given element that can be used to find() it in the same
tree later. Compared to XPath, ElementPath expressions have the advantage
of being self-contained even for documents that use namespaces.
The () method is a special case that only finds specific tags
in the tree by their name, not based on a path. That means that the
following commands are equivalent in the success case:
>>> print(next(erfind(“. //b”)))
>>> print(next((“b”)))
Note that the () method simply returns None if no match is found,
whereas the other two examples would raise a StopIteration exception.
Chapter 31 - Parsing XML with lxml - Python 101!

Chapter 31 – Parsing XML with lxml – Python 101!

In Part I, we looked at some of Python’s built-in XML parsers. In this chapter, we will look at the fun third-party package, lxml from codespeak. It uses the ElementTree API, among other things. The lxml package has XPath and XSLT support, includes an API for SAX and a C-level API for compatibility with C/Pyrex modules. Here is what we will cover:
How to Parse XML with lxml
A Refactoring example
How to Parse XML with lxml. objectify
How to Create XML with lxml. objectify
For this chapter, we will use the examples from the minidom parsing example and see how to parse those with lxml. Here’s an XML example from a program that was written for keeping track of appointments:



1181251680
040000008200E000
1181572063


1800
Bring pizza home

1234360800
Check MS Office website for updates
604f4792-eb89-478b-a14f-dd34d3cc6c21-1234360800
dismissed

Let’s learn how to parse this with lxml!
Parsing XML with lxml¶
The XML above shows two appointments. The beginning time is in seconds since the epoch; the uid is generated based on a hash of the beginning time and a key; the alarm time is the number of seconds since the epoch, but should be less than the beginning time; and the state is whether or not the appointment has been snoozed, dismissed or not. The rest of the XML is pretty self-explanatory. Now let’s see how to parse it.
from lxml import etree
def parseXML(xmlFile):
“””
Parse the xml
with open(xmlFile) as fobj:
xml = ()
root = omstring(xml)
for appt in tchildren():
for elem in tchildren():
if not
text = “None”
else:
text =
print( + ” => ” + text)
if __name__ == “__main__”:
parseXML(“”)
First off, we import the needed modules, namely the etree module from the lxml package and the StringIO function from the built-in StringIO module. Our parseXML function accepts one argument: the path to the XML file in question. We open the file, read it and close it. Now comes the fun part! We use etree’s parse function to parse the XML code that is returned from the StringIO module. For reasons I don’t completely understand, the parse function requires a file-like object.
Anyway, next we iterate over the context (i. e. the object) and extract the tag elements. We add the conditional if statement to replace the empty fields with the word “None” to make the output a little clearer. And that’s it.
Parsing the Book Example¶
Well, the result of that example was kind of boring. Most of the time, you want to save the data you extract and do something with it, not just print it out to stdout. So for our next example, we’ll create a data structure to contain the results. Our data structure for this example will be a list of dicts. We’ll use the MSDN book example here from the earlier chapter again. Save the following XML as


Gambardella, Matthew
XML Developer’s Guide
Computer 44. 95 2000-10-01 An in-depth look at creating applications
with XML.



Ralls, Kim
Midnight Rain
Fantasy 5. 95 2000-12-16 A former architect battles corporate zombies,
an evil sorceress, and her own childhood to become queen
of the world.


Corets, Eva
Maeve Ascendant 2000-11-17 After the collapse of a nanotechnology
society in England, the young survivors lay the
foundation for a new society.


Now let’s parse this XML and put it in our data structure!
def parseBookXML(xmlFile):
book_dict = {}
books = []
for book in tchildren():
book_dict[] = text
if == “book”:
(book_dict)
return books
parseBookXML(“”)
This example is pretty similar to our last one, so we’ll just focus on the differences present here. Right before we start iterating over the context, we create an empty dictionary object and an empty list. Then inside the loop, we create our dictionary like this:
The text is either or None. Finally, if the tag happens to be book, then we’re at the end of a book section and need to add the dict to our list as well as reset the dict for the next book. As you can see, that is exactly what we have done. A more realistic example would be to put the extracted data into a Book class. I have done the latter with json feeds before.
Now we’re ready to learn how to parse XML with lxml. objectify!
Parsing XML with lxml. objectify¶
The lxml module has a module called objectify that can turn XML documents into Python objects. I find “objectified” XML documents very easy to work with and I hope you will too. You may need to jump through a hoop or two to install it as pip doesn’t work with lxml on Windows. Be sure to go to the Python Package index and look for a version that’s been made for your version of Python. Also note that the latest pre-built installer for lxml only supports Python 3. 2 (at the time of writing), so if you have a newer version of Python, you may have some difficulty getting lxml installed for your version.
Anyway, once you have it installed, we can start going over this wonderful piece of XML again:
Now we need to write some code that can parse and modify the XML. Let’s take a look at this little demo that shows a bunch of the neat abilities that objectify provides.
from lxml import etree, objectify
“””Parse the XML file”””
with open(xmlFile) as f:
# returns attributes in element node as dict
attrib =
# how to extract element data
begin =
uid =
# loop over elements and print their tags and text
for e in tchildren():
print(“%s =>%s”% (, ))
print()
# how to change an element’s text
= “something else”
# how to add a new element
w_element = “new data”
# remove the py:pytype stuff
annotate(root)
eanup_namespaces(root)
obj_xml = string(root, pretty_print=True)
print(obj_xml)
# save your xml
with open(“”, “w”) as f:
(obj_xml)
f = r’pathto’
parseXML(f)
The code is pretty well commented, but we’ll spend a little time going over it anyway. First we pass it our sample XML file and objectify it. If you want to get access to a tag’s attributes, use the attrib property. It will return a dictionary of the attributes of the tag. To get to sub-tag elements, you just use dot notation. As you can see, to get to the begin tag’s value, we can just do something like this:
One thing to be aware of is if the value happens to have leading zeroes, the returned value may have them truncated. If that is important to you, then you should use the following syntax instead:
If you need to iterate over the children elements, you can use the iterchildren method. You may have to use a nested for loop structure to get everything. Changing an element’s value is as simple as just assigning it a new value.
Now we’re ready to learn how to create XML using lxml. objectify.
Creating XML with lxml. objectify¶
The lxml. objectify sub-package is extremely handy for parsing and creating XML. In this section, we will show how to create XML using the lxml. objectify module. We’ll start with some simple XML and then try to replicate it. Let’s get started!
We will continue using the following XML for our example:
Let’s see how we can use lxml. objectify to recreate this XML:
def create_appt(data):
Create an appointment XML element
appt = objectify. Element(“appointment”)
= data[“begin”]
= data[“uid”]
armTime = data[“alarmTime”]
= data[“state”]
appt. location = data[“location”]
appt. duration = data[“duration”]
bject = data[“subject”]
return appt
def create_xml():
Create an XML file
xml = ”’

”’
(“reminder”, “15”)
appt = create_appt({“begin”:1181251680,
“uid”:”040000008200E000″,
“alarmTime”:1181572063,
“state”:””,
“location”:””,
“duration”:1800,
“subject”:”Bring pizza home”})
(appt)
uid = “604f4792-eb89-478b-a14f-dd34d3cc6c21-1234360800”
appt = create_appt({“begin”:1234360800,
“uid”:uid,
“state”:”dismissed”,
“subject”:”Check MS Office website for updates”})
# remove lxml annotation
# create the xml string
obj_xml = string(root,
pretty_print=True,
xml_declaration=True)
try:
with open(“”, “wb”) as xml_writer:
except IOError:
pass
create_xml()
Let’s break this down a bit. We will start with the create_xml function. In it we create an XML root object using the objectify module’s fromstring function. The root object will contain zAppointment as its tag. We set the root’s reminder attribute and then we call our create_appt function using a dictionary for its argument. In the create_appt function, we create an instance of an Element (technically, it’s an ObjectifiedElemen**t) that we assign to our **appt variable. Here we use dot-notatio**n to create the tags for this element. Finally we return the **appt element back and append it to our root object. We repeat the process for the second appointment instance.
The next section of the create_xml function will remove the lxml annotation. If you do not do this, your XML will end up looking like the following:


1181251680
040000008200E000
1181572063


1800
Bring pizza home

1234360800
604f4792-eb89-478b-a14f-dd34d3cc6c21-1234360800
dismissed
Check MS Office website for updates
To remove all that unwanted annotation, we call the following two functions:
The last piece of the puzzle is to get lxml to generate the XML itself. Here we use lxml’s etree module to do the hard work:
The tostring function will return a nice string of the XML and if you set pretty_print to True, it will usually return the XML in a nice format too. The xml_declaration keyword argument tells the etree module whether or not to include the first declaration line (i. .
Wrapping Up¶
Now you know how to use lxml’s etree and objectify modules to parse XML. You also know how to use objectify to create XML. Knowing how to use more than one module to accomplish the same task can be valuable in seeing how to approach the same problem from different angles. It will also help you choose the tool that you’re most comfortable with.
Introduction to the Python lxml Library - Stack Abuse

Introduction to the Python lxml Library – Stack Abuse

lxml is a Python library which allows for easy handling of XML and HTML files, and can also be used for web scraping. There are a lot of off-the-shelf XML parsers out there, but for better results, developers sometimes prefer to write their own XML and HTML parsers. This is when the lxml library comes to play. The key benefits of this library are that it’s ease of use, extremely fast when parsing large documents, very well documented, and provides easy conversion of data to Python data types, resulting in easier file manipulation.
In this tutorial, we will deep dive into Python’s lxml library, starting with how to set it up for different operating systems, and then discussing its benefits and the wide range of functionalities it offers.
Installation
There are multiple ways to install lxml on your system. We’ll explore some of them below.
Using Pip
Pip is a Python package manager which is used to download and install Python libraries to your local system with ease i. e. it downloads and installs all the dependencies for the package you’re installing, as well.
If you have pip installed on your system, simply run the following command in terminal or command prompt:
$ pip install lxml
Using apt-get
If you’re using MacOS or Linux, you can install lxml by running this command in your terminal:
$ sudo apt-get install python-lxml
Using easy_install
You probably won’t get to this part, but if none of the above commands works for you for some reason, try using easy_install:
$ easy_install lxml
Note: If you wish to install any particular version of lxml, you can simply state it when you run the command in the command prompt or terminal like this, lxml==3. x. y.
By now, you should have a copy of the lxml library installed on your local machine. Let’s now get our hands dirty and see what cool things can be done using this library.
Functionality
To be able to use the lxml library in your program, you first need to import it. You can do that by using the following command:
from lxml import etree as et
This will import the etree module, the module of our interest, from the lxml library.
Creating HTML/XML Documents
Using the etree module, we can create XML/HTML elements and their subelements, which is a very useful thing if we’re trying to write or manipulate an HTML or XML file. Let’s try to create the basic structure of an HTML file using etree:
root = et. Element(‘html’, version=”5. 0″)
# Pass the parent node, name of the child node,
# and any number of optional attributes
bElement(root, ‘head’)
bElement(root, ‘title’, bgcolor=”red”, fontsize=’22’)
bElement(root, ‘body’, fontsize=”15″)
In the code above, you need to know that the Element function requires at least one parameter, whereas the SubElement function requires at least two. This is because the Element function only ‘requires’ the name of the element to be created, whereas the SubElement function requires the name of both the root node and the child node to be created.
It’s also important to know that both these functions only have a lower bound to the number of arguments they can accept, but no upper bound because you can associate as many attributes with them as you want. To add an attribute to an element, simply add an additional parameter to the (Sub)Element function and specify your attribute in the form of attributeName=’attribute value’.
Let’s try to run the code we wrote above to gain a better intuition regarding these functions:
# Use pretty_print=True to indent the HTML output
print (string(root, pretty_print=True)(“utf-8”))
Output:


<br /> <body fontsize="15"/><br /> </html><br /> There’s another way to create and organize your elements in a hierarchical manner. Let’s explore that as well:<br /> root = et. Element(‘html’)<br /> (bElement(‘head’))<br /> (bElement(‘body’))<br /> So in this case whenever we create a new element, we simply append it to the root/parent node.<br /> Parsing HTML/XML Documents<br /> Until now, we have only considered creating new elements, assigning attributes to them, etc. Let’s now see an example where we already have an HTML or XML file, and we wish to parse it to extract certain information. Assuming that we have the HTML file that we created in the first example, let’s try to get the tag name of one specific element, followed by printing the tag names of all the elements.<br /> print()<br /> html<br /> Now to iterate through all the child elements in the root node and print their tags:<br /> for e in root:<br /> head<br /> title<br /> body<br /> Working with Attributes<br /> Let’s now see how we associate attributes to existing elements, as well as how to retrieve the value of a particular attribute for a given element.<br /> Using the same root element as before, try out the following code:<br /> (‘newAttribute’, ‘attributeValue’)<br /> # Print root again to see if the new attribute has been added<br /> print(string(root, pretty_print=True)(“utf-8”))<br /> <html version="5. 0" newAttribute="attributeValue"><br /> Here we can see that the newAttribute=”attributeValue” has indeed been added to the root element.<br /> Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it! Let’s now try to get the values of the attributes we have set in the above code. Here we access a child element using array indexing on the root element, and then use the get() method to retrieve the attribute:<br /> print((‘newAttribute’))<br /> print(root[1](‘alpha’)) # root[1] accesses the `title` element<br /> print(root[1](‘bgcolor’))<br /> attributeValue<br /> None<br /> red<br /> Retrieving Text from Elements<br /> Now that we have seen basic functionalities of the etree module, let’s try to do some more interesting things with our HTML and XML files. Almost always, these files have some text in between the tags. So, let’s see how we can add text to our elements:<br /> # Copying the code from the very first example<br /> bElement(root, ‘title’, bgcolor=”red”, fontsize=”22″)<br /> # Add text to the Elements and SubElements<br /> = “This is an HTML file”<br /> root[0] = “This is the head of that file”<br /> root[1] = “This is the title of that file”<br /> root[2] = “This is the body of that file and would contain paragraphs etc”<br /> <html version="5. 0">This is an HTML file<head>This is the head of that file</head><title bgcolor="red" fontsize="22">This is the title of that fileThis is the body of that file and would contain paragraphs etc
Check if an Element has Children
Next, there are two very important things that we should be able to check, as that is required in a lot of web scraping applications for exception handling. First thing we’d like to check is whether or not an element has children, and second is whether or not a node is an Element.
Let’s do that for the nodes we created above:
if len(root) > 0:
print(“True”)
else:
print(“False”)
The above code will output “True” since the root node does have child nodes. However, if we check the same thing for the root’s child nodes, like in the code below, the output will be “False”.
for i in range(len(root)):
if (len(root[i]) > 0):
False
Now let’s do the same thing to see if each of the nodes is an Element or not:
print(element(root[i]))
True
The iselement method is helpful for determining if you have a valid Element object, and thus if you can continue traversing it using the methods we’ve shown here.
Check if an Element has a Parent
Just now, we showed how to go down the hierarchy, i. how to check if an element has children or not, and now in this section we will try to go up the hierarchy, i. how to check and get the parent of a child node.
print(tparent())
print(root[0]. getparent())
print(root[1]. getparent())
The first line should return nothing (aka None) as the root node itself doesn’t have any parent. The other two should both point to the root element i. the HTML tag. Let’s check the output to see if it is what we expect:

Retrieving Element Siblings
In this section we will learn how to traverse sideways in the hierarchy, which retrieves an element’s siblings in the tree.
Traversing the tree sideways is quite similar to navigating it vertically. For the latter, we used the getparent and the length of the element, for the former, we’ll use getnext and getprevious functions. Let’s try them on nodes that we previously created to see how they work:
# root[1] is the `title` tag
print(root[1]. getnext()) # The tag after the `title` tag
print(root[1]. getprevious()) # The tag before the `title` tag


Here you can see that root[1]. getnext() retrieved the “body” tag since it was the next element, and root[1]. getprevious() retrieved the “head” tag.
Similarly, if we had used the getprevious function on root, it would have returned None, and if we had used the getnext function on root[2], it would also have returned None.
Parsing XML from a String
Moving on, if we have an XML or HTML file and we wish to parse the raw string in order to obtain or manipulate the required information, we can do so by following the example below:
root = (‘This is an HTML fileThis is the head of that fileThis is the title of that fileThis is the body of that file and would contain paragraphs etc‘)
root[1] = “The title text has changed! ”
print(string(root, xml_declaration=True)(‘utf-8’))

This is an HTML fileThis is the head of that fileThe title text has changed! This is the body of that file and would contain paragraphs etc
As you can see, we successfully changed some text in the HTML document. The XML doctype declaration was also automatically added because of the xml_declaration parameter that we passed to the tostring function.
Searching for Elements
The last thing we’re going to discuss is quite handy when parsing XML and HTML files. We will be checking ways through which we can see if an Element has any particular type of children, and if it does what do they contain.
This has many practical use-cases, such as finding all of the link elements on a particular web page.
print((‘a’)) # No tags exist, so this will be `None`
print((‘head’))
print(ndtext(‘title’)) # Directly retrieve the the title tag’s text
This is the title of that file
Conclusion
In the above tutorial, we started with a basic introduction to what lxml library is and what it is used for. After that, we learned how to install it on different environments like Windows, Linux, etc. Moving on, we explored different functionalities that could help us in traversing through the HTML/XML tree vertically as well as sideways. In the end, we also discussed ways to find elements in our tree, and as well as obtain information from them.

Frequently Asked Questions about python lxml example

What does lxml do in Python?

lxml is a Python library which allows for easy handling of XML and HTML files, and can also be used for web scraping. There are a lot of off-the-shelf XML parsers out there, but for better results, developers sometimes prefer to write their own XML and HTML parsers.Apr 10, 2019

How do I use lxml in Python?

Implementing web scraping using lxml in PythonSend a link and get the response from the sent link.Then convert response object to a byte string.Pass the byte string to ‘fromstring’ method in html class in lxml module.Get to a particular element by xpath.Use the content according to your need.4 days ago

Does lxml come with Python?

The best way to download lxml is to visit lxml at the Python Package Index (PyPI). It has the source that compiles on various platforms. The source distribution is signed with this key. The latest version is lxml 4.6.

About the author

proxyreview

If you 're a SEO / IM geek like us then you'll love our updates and our website. Follow us for the latest news in the world of web automation tools & proxy servers!