我想知道有什么区别attrMap
and attrs
in 美丽汤 http://www.crummy.com/software/BeautifulSoup/?更具体地说,哪些标签有attrs
以及哪些有attrMap
?
>>> soup = BeautifulSoup.BeautifulSoup(source)
>>> tag = soup.find(name='input')
>>> dict(tag.attrs)['type']
u'text'
>>> tag.attrMap['type']
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
TypeError: 'NoneType' object is not subscriptable
The attrMap
字段是内部字段Tag
班级。您不应该在代码中使用它。你应该使用
value = tag[key]
tag[key] = value
这在内部映射到tag.attrMap[key]
,但只有在之后__getitem__
and __setitem__
已确保初始化self.attrMap
。这是在_getAttrMap
,这对于一个复杂的dict(self.attrs)
称呼。所以对于你的代码你将使用
>>> url = "http://stackoverflow.com/questions/8842224/"
>>> soup = BeautifulSoup.BeautifulSoup(urllib.urlopen(url).read())
>>> soup.find(name='input')
>>> tag = soup.find(name='input')
>>> tag['type']
u'text'
如果你想检查给定属性是否存在,那么你必须使用
try:
tag[key]
# found key
except KeyError:
# key not present
or
if key in dict(tag.attrs):
# found key
else:
# key not present
正如 Adam 所指出的,这是因为__contains__
方法上Tag
搜索内容,而不是属性,所以更熟悉key in tag
没有达到您预期的效果。出现这种复杂性是因为 BeautifulSoup 处理具有重复属性的 HTML 标签。因此,法线贴图(字典)还不够,因为键可以重复。但如果你想检查是否有any具有给定名称的密钥,然后key in dict(tag.attrs)
会做正确的事。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)