problems with return "None" in Python

Asked

Viewed 192 times

1

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

Attributeerror: 'Nonetype' Object has no attribute 'text'

Follows 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, the print occurs as:

(None, None, None, None)

The weird thing is that a get in http://legis.senado.gov.br/dadosabertos/senador/partidos 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 tip on how to fix this?

Thanks for your attention and help :)

1 answer

1

I’m not sure I understand why you turned xml in dictionary and then in xml back!

Anyway, I think it’s easier to work directly with the dictionary!

After you create the variable data_to_dict just run:

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

I arrived in this code there investigating the dictionary generated by xmltodict.parse()!

This print there has exactly the data you need!

  • Hello @weulerfilho, thanks for the help, really this is what I needed, I did the conversion of xml to Dict and then to xml by vacilo even hehehehehe, a doubt: is it possible to remove the "u" that precedes each data? Hugs and thanks

Browser other questions tagged

You are not signed in. Login or sign up in order to post.