首页 > 解决方案 > 尝试运行简单的 ETL 代码时出现 AttributeError

问题描述

我已经阅读了大量其他线程并且找不到解决方案,所以感谢任何人就如何解决这个问题提出的意见!

完成一门 Python 数据工程课程,这个项目是关于网络抓取的。尝试创建从 XML、CSV 和 JSON 文件中提取数据的函数时,我得到了下面的“AttributeError”。

AttributeError - 1 日志中的回溯(最近一次调用)(“提取阶段开始”)----> 2 提取数据 = 提取() 3 日志(“提取阶段结束”) 4 提取数据

in extract() 29 # 最后,处理所有 xml 文件 30 for xmlFile in glob.glob("*.xml"): ---> 31 extract_data = extract_data.append(xmlExtract(xmlFile), ignore_index=True) 32 33 return提取数据

在 xmlExtract(xmlFile) 15 root = tree.getroot() 16 对于 root 中的人:---> 17 name = person.find("name").text 18 height = float(person.find("height")。文本) 19 重量 = 浮动(person.find("weight").text)

AttributeError:“NoneType”对象没有属性“文本”

这是错误所指的代码片段:

def xmlExtract(xmlFile):
    dframe = pddf(columns=["name", "height", "weight"])
    tree = ET.parse(xmlFile)
    root = tree.getroot()
    for person in root:
        name = person.find("name").text
        height = float(person.find("height").text)
        weight = float(person.find("weight").text)
        dframe = dframe.append({"name":name, "height":height, "weight":weight}, ignore_index=True)
    return dframe

感谢任何关于从哪里开始的指示。

PS 'pdf' 是从 pandas 独特导入的 pandas.dataframe - from pandas import DataFrame as pddf- 因为我遇到了错误import pandas as pd,然后使用 pd.dataframe。

标签: python-3.xattributeerror

解决方案


错误很明显:

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

一些电话.find正在返回None。您必须None在调用.text.

def xmlExtract(xmlFile):
    dframe = pddf(columns=["name", "height", "weight"])
    tree = ET.parse(xmlFile)
    root = tree.getroot()
    for person in root:
        name = person.find("name").text if person.find("name") else None
        height = float(person.find("height").text) if person.find("height") else None
        weight = float(person.find("weight").text) if person.find("weight") else None

        dframe = dframe.append({"name": name, "height": height, "weight": weight}, ignore_index=True)
    return dframe

这段代码不是最好的。这只是一个例子。


推荐阅读