2012-03-14 169 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