problems with return "None" in Python

0
Hello, I'm trying to get data from an API for a university job, but when I try to print the data I get the following error:

  

AttributeError: 'NoneType' object has no attribute 'text'

Follow the code used:

    def list_all_political_parties():

    base_url = "http://legis.senado.gov.br/dadosabertos/senador/partidos"

    data = requests.get(url=base_url)
    data_to_dict = xmltodict.parse(data.content)
    data_to_xml = dicttoxml.dicttoxml(data_to_dict)

    root = elements.fromstring(data_to_xml)
    levels = root.findall('.//Partido')
    for level in levels:
        code = level.find('Codigo').text
        initials = level.find('Sigla').text
        name = level.find('Nome').text
        creation_date = level.find('DataCriacao').text
        print(code, initials, name, creation_date)

list_all_political_parties()

When I try to run the code without the "text" attribute, print occurs as:

  

(None, None, None, None)

The weird thing is that a get in link returns an xml with several data, so I believe that by my mistake, some data has been lost in the return.

Could someone give me a hint on how to solve this?

Thanks in advance for your attention and help:)

    
asked by anonymous 07.05.2018 / 17:28

1 answer

0

I do not know if I understand why you turn xml into dictionary and then xml back!

Anyway, I find it easier to work directly with the dictionary!

After you create the data_to_dict variable, just run:

for p in data_to_dict['ListaPartidos']['Partidos']['Partido']:
    print(p['Codigo'],p['Sigla'],p['Nome'],p['DataCriacao'])

I came up with this code by researching the dictionary generated by xmltodict.parse() !

This print there has exactly the data you need!

    
08.05.2018 / 14:28