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

如何消除这个错误呢?


当前回答

如何按类查找元素 我在使用Beautifulsoup解析带有“class”属性的html元素时遇到了麻烦。

你可以很容易地找到一个类,但如果你想找到两个类的交集,这就有点困难了,

从文档(重点添加):

如果你想搜索匹配两个或多个CSS类的标签,你应该使用CSS选择器: css_soup.select(“p.strikeout.body”) # [<p class="body strikes "></p>]

明确地说,这只选择了同时是三振型和主体类的p标记。

为了找到一组类中任意的交集(不是交集,而是并集),你可以给class_ keyword参数一个列表(从4.1.2开始):

soup = BeautifulSoup(sdata)
class_list = ["stylelistrow"] # can add any other classes to this list.
# will find any divs with any names in class_list:
mydivs = soup.find_all('div', class_=class_list) 

还要注意,findAll已从camelCase重命名为更python化的find_all。

其他回答

以下操作应该可以工作

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

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

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

直接的方法是:

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

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

下面的方法对我很有效

a_tag = soup.find_all("div",class_='full tabpublist')

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

soup.find("form",{"class":"c-login__form"})

多个

res=soup.find_all("input")
for each in res:
    print(each)