【问题标题】:TypeError: list indices must be integers or slices, not str error appears while parsing xmlTypeError: list indices must be integers or slices, not str 解析xml时出现错误
【发布时间】:2022-11-16 23:24:02
【问题描述】:

我试图为我的设备编写一个解析器。但是我不明白我在哪里犯了错误,因为我得到了错误:

print(value2['@id'])
TypeError: list indices must be integers or slices, not str

您可能会在下面看到我的代码:

import requests
import xmltodict 

url = 'http://192.168.1.8:8060/query/apps'
text = requests.get(url).text
#content = """
#<?xml version="1.0" encoding="UTF-8"?>
#<apps>
#<app id="31012" type="menu" #version="2.0.53">Vudu Movie &amp; #TV Store</app>
#</apps>
#"""
text = text.split('\n')
text = text[1:]
text = ''.join(text)
data = xmltodict.parse(text)
data = dict(data)

for key1, value1 in data.items():
  for key2, value2 in value1.items():
    print(value2['@id'])
    print(value2['@type'])
    print(value2['#text'])

有人可以帮我吗?

【问题讨论】:

    标签: python-3.x xml parsing


    【解决方案1】:
    import requests
    import xmltodict 
    
    url = 'http://192.168.1.8:8060/query/apps'
    text = requests.get(url).text
    #content = """
    #<?xml version="1.0" encoding="UTF-8"?>
    #<apps>
    #<app id="31012" type="menu" #version="2.0.53">Vudu Movie &amp; #TV Store</app>
    #</apps>
    #"""
    text = text.split('
    ')
    text = text[1:]
    text = ''.join(text)
    data = xmltodict.parse(text)
    data = dict(data)
    
    for key1, value1 in data.items():
        for key2, value2 in value1.items():
            if isinstance(value2, list):
                for item in value2:
                    print(item['@id'])
                    print(item['@type'])
                    print(item['#text'])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-28
      • 1970-01-01
      • 1970-01-01
      • 2019-07-23
      • 2023-02-07
      • 2022-08-17
      • 2019-07-23
      • 2013-09-26
      相关资源
      最近更新 更多