Neo Neo - 1 year ago 78
HTML Question

How to find elements by class

I'm having trouble parsing html elements with "class" attribute using Beautifulsoup. The code looks like this

soup = BeautifulSoup(sdata)
mydivs = soup.findAll('div')
for div in mydivs:
if (div["class"]=="stylelistrow"):
print div

I get an error on the same line "after" the script finishes.

File "./", line 130, in getlanguage
if (div["class"]=="stylelistrow"):
File "/usr/local/lib/python2.6/dist-packages/", line 599, in __getitem__
return self._getAttrMap()[key]
KeyError: 'class'

How do I get rid or this error?

Answer Source

You can refine your search to only find those divs with a given class:

mydivs = soup.findAll("div", { "class" : "stylelistrow" })
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download