带有可选标签的Python BeautifulSoup

时间:2011-06-30 08:10:08

标签: python xml beautifulsoup

让我举一个例子:

    from BeautifulSoup import BeautifulStoneSoup
    root = '''  <all2>
                    <images>
                        <image>
                            <name> Picture </name>
                            <url> www.thing.com</url>
                        </image>
                        <image> 
                            <name> Another one! </name>
                        </image>
                    </images>
                </all2>
                      '''

soup = BeautifulStoneSoup(root)
for img in soup.all2.images.findAll("image"):
    iname = img.i_name
    iurl = img.url
    print iname
    print iurl

让标签是可选的。在这种情况下,第二次迭代将无法找到标记,并将抛出异常:

AttributeError:'NoneType'对象没有属性'renderContents'

如果没有出现可选标签,我希望iur为None。这可能吗?或者我的XML理解是错误的。

1 个答案:

答案 0 :(得分:1)

'nameTag'你想要什么?

BeautifulSoup文档明确告诉您使用

  iname = img.name.renderContents()
  iurl = img.url.renderContents()

在这里发明新语法或语义的零理由

相关问题