Next / Previous / Contents / TCC Help System / NM Tech homepage

9.8. Element.get(): Retrieve an attribute value with defaulting

There are two ways you can try to get an attribute value from an Element instance. See also the .attrib dictionary in Section 9.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.

Here's an example:

>>> from lxml import etree
>>> node = etree.fromstring('<mount species="Jackalope"/>')
>>> print node.get('species')
>>> print node.get('source')
>>> print node.get('source', 'Unknown')