(Python) AttributeError: ‘NoneType’ object has no attribute ‘text’

Instead of checking if child.find('EmentaMateria').text is not None, you should make sure that child.find('EmentaMateria') is not None first.

Also, you should store the returning value of child.find('EmentaMateria') to avoid calling it twice.

Lastly, you should assign ementa a default value if child.find('EmentaMateria') is None; otherwise your print function below will be referencing an un-initialized variable.


if child.find('EmentaMateria').text is not None:
    ementa = child.find('EmentaMateria').text


node = child.find('EmentaMateria')
if node is not None:
    ementa = node.text
    ementa = None

Alternatively, you can use the built-in function getattr to do the same without a temporary variable:

ementa = getattr(child.find('EmentaMateria'), 'text', None)

Leave a Comment