TypeError:“ NoneType”对象不可用于xmltodict下标

时间:2019-03-14 10:05:34

标签: python xml nonetype xmltodict

for i in range(1,3200):
    input_file = 'ProductGet'
    fp = open(input_file+str(i)+'.xml' ,encoding='utf8')
    tree = etree.parse(fp)
    ProductID = tree.xpath('/Responses/Response/Data/Product/ProductID/text()')
    with open(input_file+str(i)+'.xml', errors='ignore') as fd:
        doc = xmltodict.parse(fd.read())
    berrak = doc['Responses']['Response']['Data']['Product']
    for ii in range(0,len(ProductID)):
        print(berrak[ii]['Variations']['Variation']['VariationIsLive'])

我有一些.xml文件集,我的脚本正在将所有文件从1到3200打开。但是,当它随机解析时,它会为NoneType这部分显示berrak[ii]['Variations']['Variation']['VariationIsLive']消息。我检查了这个文件,一切看起来都很好。我的问题是如何将NoneType元素转换为字符串?

1 个答案:

答案 0 :(得分:0)

您应该保护代码不受此问题的影响

for ii in range(0,len(ProductID)):
    variations = berrak[ii].get('Variations')
    if variations:
        variation = variations.get(''Variation'')
        if variation:
            is_live = variation.get('VariationIsLive')
            if is_live is not None:
                print(is_live)