xml – (Python) AttributeError: NoneType object has no attribute text
xml – (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.
Change:
if child.find(EmentaMateria).text is not None:
ementa = child.find(EmentaMateria).text
to:
node = child.find(EmentaMateria)
if node is not None:
ementa = node.text
else:
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)
If you are using the code to parse an xml file, open the xml file with a text editor and inspect the tags. In my case there were some rogue tags at the end. Once i removed those, the code worked as expected.