Jack
Jack

Reputation: 355

How to grab the attribute value using beautifulSoup?

Code:

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

Output

[<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>]

Now how will I grab the attributes value like the data between tag that is System Memory and so on. Any help is appreciated.

Upvotes: 2

Views: 2213

Answers (2)

Jakub M.
Jakub M.

Reputation: 33867

To get <...>this</...> you should use contents field, so in your case it would be:

print data.description.contents

To get attributes access them as they were a dictionary

print data.size['units']

And to iterate all the tags, use findAll that you already know:

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

Upvotes: 4

nate_weldon
nate_weldon

Reputation: 2349

beautifulsoup can create a tree. you can then iterate over that tree and get the attributes

check out the following link http://www.crummy.com/software/BeautifulSoup/bs3/documentation.html#TheattributesofTags

Upvotes: 1

Related Questions