. Advertisement .
..3..
. Advertisement .
..4..
For the problem “attributeerror: ‘nonetype’ object has no attribute ‘text’.” I tried to fix it, but It doesn’t work and returns the result I want. Here is my program:
url = 'http://legis.senado.leg.br/dadosabertos/senador/4988/autorias'
import requests
from xml.etree import ElementTree
response = requests.get(url, stream=True)
response.raw.decode_content = True
tree = ElementTree.parse(response.raw)
root = tree.getroot()
for child in root.iter('Materia'):
if child.find('EmentaMateria').text is not None:
ementa = child.find('EmentaMateria').text
for child_IdMateria in child.findall('IdentificacaoMateria'):
anoMateria = child_IdMateria.find('AnoMateria').text
materia = child_IdMateria.find('NumeroMateria').text
siglaMateria = child_IdMateria.find('SiglaSubtipoMateria').text
print('Ano = '+anoMateria+' | Numero Materia = '+materia+' | tipo = '+siglaMateria+' | '+ementa)
and
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-70-77e5e1b79ccc> in <module>()
11
12 for child in root.iter('Materia'):
---> 13 if not child.find('EmentaMateria').text is None:
14 ementa = child.find('EmentaMateria').text
15
AttributeError: 'NoneType' object has no attribute 'text'
has occurred. I’ve checked the entire command line, but still can’t find the mistake.
The cause: A call to an attribute out of an object which does not present or is not supported results in an exception known as an attribute error in the Python program.
Solution: You should follow my way to fix attributeerror: ‘nonetype’ object has no attribute ‘text’:
You should verify that
child.find('EmentaMateria')
is notNone
before determining ifchild.find('EmentaMateria').text
is notNone
.Additionally, in order to prevent calling
child.find('EmentaMateria')
twice, you need also keep the returning value.Finally, whether
child.find('EmentaMateria')
returnsNone
, you need to assignementa
to a default value because otherwise the followingprint
function will reference an uninitialized variable.Alter:
with:
As an alternative, you can accomplish the same thing without a temporary variable by using the built-in function
getattr
:You can inspect the tags if you’re using the code to read an xml format file. In my case, there were some rogue tag at the end. I was able to remove them and the code worked as expected.