项目环境:
我的环境:Window10,Python3.12,Anaconda3,Pycharm2024.3.4
问题描述:
找不到’text’这个对象
部分代码:
Traceback (most recent call last):
File "D:\IT DateFiles\PyDate\FQC\main.py", line 55, in <module>
m_text = draw_item.find("m_text").text
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'text'
原因分析:
1.遍历的XML 文件中某些 节点可能没有 <m_text> 这个子节点;
2.我使用的ElementTree 的 find() 方法在找不到指定节点时返回了 None。
部分代码:
# 遍历 XML 文件中的 <DrawItemInfo> 节点
m_texts = [] # 用于存储符合条件的 m_text
for draw_item in root.findall("DrawItemInfo"):
m_color = draw_item.find("m_color").text
m_text = draw_item.find("m_text").text
# 检查 m_color 是否为 ffff0000 且 m_text 不是 "NG"
if m_color == "ffff0000" and m_text != "NG":
print(m_text)
m_texts.append(m_text)
解决:
在尝试访问 <m_text> 的内容之前,先去检查它是否存在。
这里可以通过检查 find() 方法的返回值是否为 None 来避免这个错误。
部分代码:
# 遍历 XML 文件中的 <DrawItemInfo> 节点
m_texts = [] # 用于存储符合条件的 m_text
for draw_item in root.findall("DrawItemInfo"):
m_color = draw_item.find("m_color")
m_text_element = draw_item.find("m_text") # 获取 m_text 元素
# 检查 m_color 是否存在且值为 ffff0000
if m_color is not None and m_color.text == "ffff0000":
# 检查 m_text 元素是否存在且内容不是 "NG"
if m_text_element is not None and m_text_element.text != "NG":
m_texts.append(m_text_element.text)
希望本文对你解决:XXXX问题有所帮助。
SueMagic wish you a happy coding~
有疑问可联系我。
更多精彩链接/友情链接:
问题解决:Fatal Python error: initfsencoding: unable to load the file system codec