如何找到类元素 [英] How to find elements by class

查看:178
本文介绍了如何找到类元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在用Beautifulsoupclass属性的麻烦解析HTML元素。在code看起来像这样

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 "./beautifulcoding.py", line 130, in getlanguage
  if (div["class"]=="stylelistrow"):
File "/usr/local/lib/python2.6/dist-packages/BeautifulSoup.py", line 599, in __getitem__
   return self._getAttrMap()[key]
KeyError: 'class'

我如何摆脱或这个错误?

How do I get rid or this error?

推荐答案

您可以细化搜索,只找到一个给定的类这些div:

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

mydivs = soup.findAll("div", { "class" : "stylelistrow" })

这篇关于如何找到类元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆