I would like to know whats the difference between attrMap and attrs in BeautifulSoup? To be more specific, which tags have attrs and which have 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
attrMapfield is an internal field in theTagclass. You should not use it in your code. You should instead useThis maps internally to
tag.attrMap[key], but only after__getitem__and__setitem__have made sure to initializeself.attrMap. This is done in_getAttrMap, which is nothing by a complicateddict(self.attrs)call. So for your code you’ll useIf you want to check for the existance of a given attribute, then you must use
or
As pointed out by Adam, this is because the
__contains__method onTagsearches the content, not the attributes, and so the more familiarkey in tagdoesn’t do what you would expect. This complexity arises because BeautifulSoup handles HTML tags with repeated attributes. So a normal map (dictionary) isn’t quite enough since the keys can be duplicated. But if you want to check if there is any key with a given name, thenkey in dict(tag.attrs)will do the right thing.