使用python ElementTree访问子级的子级属性

使用python ElementTree访问子级的子级属性,python,xml,elementtree,Python,Xml,Elementtree,xml文件: 其中循环中的“成员=帧” 一, AttributeError:“非类型”对象没有属性“attrib” 二, AttributeError:“list”对象没有属性“attrib”,因为您使用的是ElementTree,并且假设您的代码如下所示: members = """ <doc> <frame id="18" source="vd01"> <rectangle

xml文件:

其中循环中的“成员=帧”

一,

AttributeError:“非类型”对象没有属性“attrib”

二,


AttributeError:“list”对象没有属性“attrib”

,因为您使用的是ElementTree,并且假设您的代码如下所示:

members = """
<doc>
   <frame id="18" source="vd01">
      <rectangle id="1" height="87" width="976" y="889" x="414"/>
   </frame>
   <frame id="19" source="vd01">
      <rectangle id="1" height="87" width="976" y="889" x="333"/>
   </frame>
</doc>
"""
输出:

414
333
编辑:

更改xml后,将
for
循环更改为:

for frame in doc.findall('.//frame[rectangle]'):    
      for rec in frame.findall('.//rectangle'):
         print(rec.attrib['x'])
现在输出应该是:

414
300
316
635

请发一封信。现在还不清楚您使用的是什么包/模块。它给出了until member.find('rectangle'),但当我们添加member.find('rectangle').attrib['x']时,它说AttributeError:'NoneType'对象没有属性'attrib'。maryammehboob然后请编辑您的问题并添加一个简短的,您正在使用的html的代表性示例。我编辑了我的问题。@maryammehboob请参阅编辑的答案。JackFleeting,感谢您为我编辑了这么多的答案。我错过了内环。
members = """
<doc>
   <frame id="18" source="vd01">
      <rectangle id="1" height="87" width="976" y="889" x="414"/>
   </frame>
   <frame id="19" source="vd01">
      <rectangle id="1" height="87" width="976" y="889" x="333"/>
   </frame>
</doc>
"""
import xml.etree.ElementTree as ET
doc = ET.fromstring(members)
for frame in doc.findall('.//frame'):         
       print(frame.attrib['x'])
414
333
for frame in doc.findall('.//frame[rectangle]'):    
      for rec in frame.findall('.//rectangle'):
         print(rec.attrib['x'])
414
300
316
635