Python BeautiulstoneSop属性错误:';NavigableString';对象没有属性';子标签';
我正在尝试使用BeautifulSoup来解析一些XML,看起来像Python BeautiulstoneSop属性错误:';NavigableString';对象没有属性';子标签';,python,xml,beautifulsoup,Python,Xml,Beautifulsoup,我正在尝试使用BeautifulSoup来解析一些XML,看起来像 <a> <b> <c> <d attr="x"> <e> </e> <name> </name> </d> </c> <c> ... <c> <
<a>
<b>
<c>
<d attr="x">
<e>
</e>
<name>
</name>
</d>
</c>
<c>
...
<c>
</b>
</a>
但这并不是:
for subtag in soup.a.b.c:
print subtag.d.e
相反,它给出了以下错误:
AttributeError: 'NavigableString' object has no attribute 'd'
这有点不合时宜:
print soup.a.b.c.d.name
仅输出d
我做错了什么?我怀疑对于第二个问题,我将不得不使用
find()
,因为该对象已经具有name
属性。有更好的方法吗?您会得到一个AttributeError
,因为当您循环标记
实例时。也许你想试试:
soup.a.b.c.findChildren()
#[<d attr="x">
#<e>
#</e>
#<name>
#</name>
#</d>, <e>
#</e>, <name>
#</name>]
设置代码以供参考:
from BeautifulSoup import BeautifulStoneSoup as bss
soup = bss(markup)
这:
仅输出d
这是因为name
与标记对象的内置name
属性冲突。根据上的文档,您可以改用soup.a.b.c.d.nameTag
属性错误在其他答案中得到了很好的解释。如果要提取整个文档中的每个(d,e,name)
三元组,无论d
标记出现在何处,都可以执行以下操作:
soup = BeautifulStoneSoup(doc)
for d in soup.findAll('d'):
print (d, d.e, d.nameTag)
这个解析的目标是什么?是否要提取第一个
a.b.c
元素中包含的每个d
元素的第一个e
元素?我想要所有(d
,e
,name
)组。
from BeautifulSoup import BeautifulStoneSoup as bss
soup = bss(markup)
print soup.a.b.c.d.name
soup = BeautifulStoneSoup(doc)
for d in soup.findAll('d'):
print (d, d.e, d.nameTag)