There are two ways you can try to get an attribute value
from an Element instance. See also the
.attrib dictionary in Section 8.1, “Attributes of an Element instance”.
The .get() method on an Element instance also attempts to retrieve an
attribute value. The advantage of this method is that
you can provide a default value that is returned if the
element in question does not actually have an attribute
by the given name.
Here is the general form, for some Element
instance .
E
E.get ( key, default=None )
The key argument is the name of the
attribute whose value you want to retrieve.
If has an attribute
by that name, the method returns that attribute's value
as a string.
E
If has
no such attribute, the method returns the Edefault argument, which itself has a default
value of None.
Here's an example:
>>> from lxml import etree
>>> node = etree.fromstring('<mount species="Jackalope"/>')
>>> print node.get('species')
Jackalope
>>> print node.get('source')
None
>>> print node.get('source', 'Unknown')
Unknown
>>>