我想知道attrMap和BeautifulSoup中的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 "", line 1, in
TypeError: 'NoneType' object is not subscriptable
解决方法:
attrMap字段是Tag类中的内部字段.您不应在代码中使用它.您应该改用
value = tag[key]
tag[key] = value
这在内部映射到tag.attrMap [key],但仅在__getitem__和__setitem__确定初始化self.attrMap之后.这是在_getAttrMap中完成的,通过复杂的dict(self.attrs)调用可以完成任何操作.因此,对于您的代码,您将使用
>>> url = "https://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__方法搜索的是内容而不是属性,因此tag中更熟悉的键不能满足您的期望.之所以出现这种复杂性,是因为BeautifulSoup处理具有重复属性的HTML标签.因此,法线图(字典)还不够,因为可以复制键.但是,如果要检查是否存在具有给定名称的任何键,则键入dict(tag.attrs)将做正确的事情.
标签:beautifulsoup,python