You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

XML转CSV遇AttributeError:NoneType无text属性,求EAN字段读取方案

解决Python读取XML转CSV时EAN字段的AttributeError问题

在将XML文件转换为CSV的Python代码中,读取ean字段时触发AttributeError: 'NoneType' object has no attribute 'text'错误,移除EAN相关代码后程序可正常运行。需要修改代码以安全读取EAN字段,同时保留full_name、item_name、price、in_stock等指定字段的读取功能。

XML示例片段

<?xml version="1.0" encoding="UTF-8"?>
<catalogue date="2022-08-23 15:58" GMT= "+1">
    <product>
        <id>14726</id>
        <manufacturer>Kieslect</manufacturer>
        <item_name>Kieslect Smart Tag Lite Pack (2 x Black and 1 x White) Black White</item_name>
        <sku>157003-126899-18495_HU03</sku>
        <warehouse>HU03</warehouse>
        <bar_code>157003-126899-18495</bar_code>
        <in_stock><![CDATA[&amp;lt;50]]></in_stock>
        <exp_delivery><![CDATA[0]]></exp_delivery>
        <delivery_date>0000-00-00</delivery_date>
        <price>20.00</price>
        <image>https://images.bluefinmobileshop.com/1637675528/large-full/kieslect-smart-tag-lite-pack-2-x-black-and-1-x-white-black-white.jpg</image>
        <properties>            
            <full_name>Kieslect Smart Tag Lite (6974377570098)</full_name>
            <ean>6974377570098</ean>
        </properties>
        <category>accessory</category>
    </product>
</catalogue>

原代码问题分析

  1. 未处理节点缺失:直接调用find().text,若某个product没有properties节点,或properties下无ean/full_name节点,会返回None并触发AttributeError
  2. 变量赋值错误:rows中item_name错误赋值为full_name,未使用正确的字段值
  3. 无默认值初始化:若没有properties节点,full_name和ean变量会未定义,导致追加数据行时报错

修改后的完整代码

import xml.etree.ElementTree as Xet
import pandas as pd

cols = ["full_name", "item_name", "price", "in_stock", "ean"]
rows = []

# 解析XML文件
xmlparse = Xet.parse('in.xml')
root = xmlparse.getroot()

for product in root.findall('.//product'):
    # 读取基础字段,处理节点不存在的情况
    item_name = product.find("item_name").text if product.find("item_name") is not None else None
    in_stock = product.find("in_stock").text if product.find("in_stock") is not None else None
    price = product.find("price").text if product.find("price") is not None else None
    
    # 初始化properties下的字段为默认值
    full_name = None
    ean = None
    
    # 获取properties节点,避免冗余循环
    properties = product.find('properties')
    if properties is not None:
        full_name = properties.find('full_name').text if properties.find('full_name') is not None else None
        ean = properties.find('ean').text if properties.find('ean') is not None else None
    
    # 追加数据行,修正item_name赋值错误
    rows.append({
        "full_name": full_name,
        "item_name": item_name,
        "price": price,
        "in_stock": in_stock,
        "ean": ean
    })

# 生成DataFrame并保存为CSV
df = pd.DataFrame(rows, columns=cols)
df.to_csv('out.csv', index=False)

关键修改点

  • 空值安全处理:对每个find()结果先判断是否为None,再读取.text,彻底避免AttributeError
  • 默认值初始化:提前给full_name和ean赋值为None,确保即使无properties节点也不会出现未定义变量
  • 简化节点获取:直接用product.find('properties')获取单个节点,替代原代码的findall循环,减少冗余
  • 修正赋值错误:将rows中的item_name改为正确的变量,不再错误复用full_name

内容的提问来源于stack exchange,提问作者Jacek Kupiec

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 14:45:33