Difference between attrMap and attrs in beautifulS

2020-07-22 18:47发布

问题:

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

回答1:

The attrMap field is an internal field in the Tag class. You should not use it in your code. You should instead use

value = tag[key]
tag[key] = value

This maps internally to tag.attrMap[key], but only after __getitem__ and __setitem__ have made sure to initialize self.attrMap. This is done in _getAttrMap, which is nothing by a complicated dict(self.attrs) call. So for your code you'll use

>>> 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'

If you want to check for the existance of a given attribute, then you must use

try:
    tag[key]
    # found key
except KeyError:
    # key not present

or

if key in dict(tag.attrs):
    # found key
else:
    # key not present

As pointed out by Adam, this is because the __contains__ method on Tag searches the content, not the attributes, and so the more familiar key in tag doesn'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, then key in dict(tag.attrs) will do the right thing.