3

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
Martin Geisler
  • 72,968
  • 25
  • 171
  • 229
amulllb
  • 3,036
  • 7
  • 50
  • 87

1 Answers1

3

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.

Martin Geisler
  • 72,968
  • 25
  • 171
  • 229
  • Great Answer. Another question related to this - How do I know if an attribute is present? From the above example, I could do - tag.has_key('type') but after running PEP8 against the code, it says has_key has been deprecated and use 'in' instead? Any thoughts? I can't do tag.keys()?! – amulllb Jan 12 '12 at 21:18
  • So: 'if "type" in tag: whatever()' – AdamKG Jan 12 '12 at 21:31
  • @AdamKG - Yes!! But doing the same returns False. So "if 'type' in tag:whatever()" does not work :( – amulllb Jan 12 '12 at 21:38
  • So you mean 'assert "type" not in tag; assert tag["type"] == "text"' doesn't raise any assertion errors? EDIT: just tried it, apparently so. That's weird behavior on BeautifulSoup's part... – AdamKG Jan 12 '12 at 21:43
  • So just go ahead and use .has_key() - it's not PEP8-compliant, but BeautifulSoup isn't properly emulating a dictionary here - \_\_contains\_\_ (what's called for the 'in' operator) checks against self.contents instead of the attributes. – AdamKG Jan 12 '12 at 21:46
  • Ya... `>>> assert tag['type'] == 'text' >>> assert 'type' not in tag >>> ` don't throw error. – amulllb Jan 12 '12 at 21:46
  • I've updated the answer with a bit about how to search for keys (attributes) in the tags. – Martin Geisler Jan 12 '12 at 22:12