我有这样的XML

#filename sample.xml
<tag>
<tag1>
<tag2 property="something"/>
<tag2 property="something1"/>
<tag2 property="something2">value</tag2>
<tag2 property="something3">
<tag3>
<tag4 data="data1"/>
<tag4 data="data2"/>
</tag3>
</tag2>
</tag1>
</tag>


我要提取'data1''data2'。我正在尝试这样的事情:

f=open('sample.xml')
fdata=f.read()
xmldata=BeautifulSoup(fadata)
print (xmldata.tag.tag1.tag2.tag3.tag4["data"])


但这会引发错误:

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

最佳答案

print功能由于多个tag2而失败。一种解决方案是使用.findAll('tag2')检索所有标签。

这是一个工作示例:

#! /usr/bin/python

from bs4 import BeautifulSoup
f=open('sample.xml')
fdata=f.read()
xmldata=BeautifulSoup(fdata)

alltags2 = xmldata.tag.tag1.findAll('tag2')

for tag2 in alltags2:
    alltags3 = tag2.findAll('tag3')
    for tag3 in alltags3:
        alltags4 = tag3.findAll('tag4')
        for tag4 in alltags4:
            print "The data I got was :\"%s\"" % (tag4["data"])


亲切的问候,

10-07 16:34