用beautifulsoup获取id名称

时间:2012-11-18 03:41:02

标签: python beautifulsoup

如果我有文字:

text = '<span id="foo"></span> <div id="bar"></div>'

文本可以更改(可能没有任何ID),我怎么能使用BeautifulSoup获取id名称而不管标记名称(返回['foo','bar'])。我对BeautifulSoup没有经验,并且对完成这项任务感到困惑。

1 个答案:

答案 0 :(得分:10)

您需要获取带有id属性的标记,然后将id属性的值返回到字符串,例如

from BeautifulSoup import BeautifulSoup
text = '<span id="foo"></span> <div id="bar"></div>'
pool = BeautifulSoup(text)
result = []
for tag in pool.findAll(True,{'id':True}) :
    result.append(tag['id'])

和结果

>>> result
[u'foo', u'bar']