开发者

Python BeautifulSoup with Optional Tags

Let me set up an example:

    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 ina开发者_运维问答me
    print iurl

Let the tag be optional. In this case, the second iteration will fail to to find a tag, and an exception will be thrown:

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

I would like for iurl to be None if an optional tag does not appear. Is this possible? Or is my XML understanding wrong.


What do you want with 'nameTag'???

The BeautifulSoup documentation clearly tells you to use

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

Zero reason to invent new syntax or semantics here

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜