我在使用Beautifulsoup解析带有“class”属性的HTML元素时遇到了麻烦。代码看起来像这样

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

我在脚本完成后的同一行上得到一个错误。

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'

如何消除这个错误呢?


当前回答

你可以使用BS3优化你的搜索,只找到那些给定类的div:

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

其他回答

这可以让我访问class属性(在beautifulsoup 4上,与文档所说的相反)。KeyError返回的是一个列表,而不是字典。

for hit in soup.findAll(name='span'):
    print hit.contents[1]['class']

直接的方法是:

soup = BeautifulSoup(sdata)
for each_div in soup.findAll('div',{'class':'stylelist'}):
    print each_div

确保你使用了findAll的外壳,它不是findAll

你可以使用BS3优化你的搜索,只找到那些给定类的div:

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

以下操作应该可以工作

soup.find('span', attrs={'class':'totalcount'})

用你的类名替换'totalcount',用你正在寻找的标签替换'span'。此外,如果类包含多个带空格的名称,只需选择一个并使用即可。

附注:这个函数用给定的条件找到第一个元素。如果你想找到所有的元素,那么将'find'替换为'find_all'。

或者我们可以使用lxml,它支持xpath和非常快!

from lxml import html, etree 

attr = html.fromstring(html_text)#passing the raw html
handles = attr.xpath('//div[@class="stylelistrow"]')#xpath exresssion to find that specific class

for each in handles:
    print(etree.tostring(each))#printing the html as string