带有可选标签的 Python 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' object has no attribute 'renderContents'
如果没有出现可选标签,我希望 iurl 为 None 。这可能吗?或者是我对XML的理解错误。
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 iname
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你想要“nameTag”做什么???
BeautifulSoup 文档清楚地告诉您使用
零理由在这里发明新的语法或语义
What do you want with 'nameTag'???
The BeautifulSoup documentation clearly tells you to use
Zero reason to invent new syntax or semantics here