2012-03-14 168 views
2

代码:如何使用beautifulSoup获取属性值?

soup=BeautifulSoup(f.read()) 
data=soup.findAll('node',{'id':'memory'}) 
print data 

输出

[<node id="memory" claimed="true" class="memory" handle="DMI:000E"> 
<description> 
    System Memory 
</description> 
<physid> 
    e 
</physid> 
<slot> 
    System board or motherboard 
</slot> 
<size units="bytes"> 
    3221225472 
</size> 
<capacity units="bytes"> 
    3221225472 
</capacity> 
</node>] 

现在我怎么会抢的属性值,像标签之间的数据是系统内存等。任何帮助表示赞赏。

回答

2

要获得<...>this</...>你应该使用contents场,所以在你的情况将是:

print data.description.contents 

要获得attributes访问他们,因为他们是一个字典

print data.size['units'] 

并重复所有标签,请使用您已知的findAll

for node in data.findAll(True): 
    # do stuff on node