我正在尝试获取标记Name
的所有XML属性。
出现此错误:
AttributeError: 'NoneType' object has no attribute 'attrs'
当我执行以下代码时:
import BeautifulSoup as bs
xml = '''
<Product Code="1" HighPic="http://upload.wikimedia.org/wikipedia/commons/thumb/5/5f/Linksys48portswitch.jpg/220px-Linksys48portswitch.jpg" HighPicHeight="320" HighPicSize="37217" HighPicWidth="400" ID="35" Title="Demo Product">
<Category ID="23">
<Name ID="57" Value="Switches" langid="1"/>
</Category>
</Product>'''
doc = bs.BeautifulSoup(xml)
div = doc.find("Name")
for attr, val in div.attrs:
print "%s:%s" % (attr, val)
我将标记"Name"
更改为"name"
,然后就可以了。
当标记名称包含大写字母时,为什么会出现此错误?
答案 0 :(得分:3)
BeautifulSoup主要是一个HTML解析库。它也可以处理XML,但根据HTML规范,所有标签都是小写的。引用BeautifulSoup documentation:
由于HTML标记和属性不区分大小写,因此所有三个HTML解析器都将标记和属性名称转换为小写。也就是说,标记
<TAG></TAG>
将转换为<tag></tag>
。如果要保留混合大小写或大写标记和属性,则需要将文档解析为XML。
是一个XML modus,其中标签是区分大小写且不是小写的,但这需要安装lxml
库。由于lxml
是C扩展程序库,因此Google App Engine不支持此功能。
改为使用ElementTree API:
import xml.etree.ElementTree as ET
root = ET.fromstring(xml)
div = root.find('.//Name')
for attr, val in div.items():
print "%s:%s" % (attr, val)
答案 1 :(得分:0)
在BeautifulSoup 4中,您可以使用
doc = bs.BeautifulSoup(xml, "xml")
div = doc.find("Name")
这应该有用。