用beautifulsoup获取id名称

Hai*_*irr 5 python beautifulsoup

如果我有文字:

text = '<span id="foo"></span> <div id="bar"></div>'
Run Code Online (Sandbox Code Playgroud)

如果文本可以更改(可能没有任何ID),我怎么能使用BeautifulSoup获取id名称而不管标记名称(返回['foo','bar']).我对BeautifulSoup没有经验,并且在执行此任务时感到困惑.

Pat*_*g J 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'])
Run Code Online (Sandbox Code Playgroud)

和结果

>>> result
[u'foo', u'bar']
Run Code Online (Sandbox Code Playgroud)