BeautifulStoneSoup AttributeError:“NavigableString”对象没有属性“subtag”

2024-06-16 10:11:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用BeautifulSoup来解析一些看起来像

<a>
  <b>
    <c>
      <d attr="x">
        <e>
        </e>
        <name>
        </name>
      </d>
    </c>
    <c>
      ...
    <c>
  </b>
</a>

但我不知道如何在循环中访问ename。这是有效的:

print soup.a.b.c.d.e

但这并不是:

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属性。有更好的办法吗?


Tags: nonameinforobject错误attributeattr
2条回答

你得到一个AttributeError,因为BSS returns ^{}s当你循环Tag实例时。也许你想试试:

soup.a.b.c.findChildren()
#[<d attr="x">
#<e>
#</e>
#<name>
#</name>
#</d>, <e>
#</e>, <name>
#</name>]

关于问题w/name:它是specified as an attribute,但是您可以改为:

soup.a.b.c.d.findChildren('name')
#[<name>
#</name>]

设置参考代码:

from BeautifulSoup import BeautifulStoneSoup as bss
soup = bss(markup)

这个:

print soup.a.b.c.d.name

仅输出d.

这是因为name与标记对象的内置name属性冲突。根据using tags names as members上的文档,可以使用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)

相关问题 更多 >