beautifulSoup中attrMap和attrs的区别
我想知道在BeautifulSoup中,attrMap
和attrs
有什么区别?更具体一点,哪些标签有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
1 个回答
3
attrMap
字段是Tag
类中的一个内部字段。你在代码中不应该使用它。你应该使用
value = tag[key]
tag[key] = value
这个内部会映射到tag.attrMap[key]
,但只有在__getitem__
和__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
或者
if key in dict(tag.attrs):
# found key
else:
# key not present
正如Adam所指出的,这个问题是因为Tag
类中的__contains__
方法是用来搜索内容的,而不是属性。因此,像key in tag
这样的用法并不会得到你预期的结果。这种复杂性是因为BeautifulSoup处理HTML标签时,可能会有重复的属性。所以普通的映射(字典)并不够用,因为键可能会重复。但如果你想检查是否有任何一个键的名字是给定的,那么key in dict(tag.attrs)
就能正确工作。