我在使用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'

如何消除这个错误呢?


当前回答

或者我们可以使用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

其他回答

关于@Wernight对上面关于部分匹配的答案的评论…

你可以部分匹配:

<div class="stylelistrow"> and <div class="stylelistrow button">

西班牙凉菜汤:

from gazpacho import Soup

my_divs = soup.find("div", {"class": "stylelistrow"}, partial=True)

两者都将被捕获并作为Soup对象列表返回。

具体到BeautifulSoup 3:

soup.findAll('div',
             {'class': lambda x: x 
                       and 'stylelistrow' in x.split()
             }
            )

会找到所有这些:

<div class="stylelistrow">
<div class="stylelistrow button">
<div class="button stylelistrow">

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

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

或者我们可以使用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

从文档中可以看到:

从Beautiful Soup 4.1.2开始,你可以使用关键字参数class_通过CSS类进行搜索:

soup.find_all("a", class_="sister")

在这种情况下是:

soup.find_all("div", class_="stylelistrow")

它还适用于:

soup.find_all("div", class_="stylelistrowone stylelistrowtwo")