python - 如何按类查找元素
我使用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'
我该怎么摆脱或这个错误?
9个解决方案
430 votes
您可以优化搜索,只使用BS3查找具有给定类的div:
mydivs = soup.findAll("div", {"class": "stylelistrow"})
Klaus Byskov Pedersen answered 2019-02-15T20:12:35Z
166 votes
从文档:
从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")
jmunsch answered 2019-02-15T20:13:13Z
35 votes
更新:2016年在最新版本的beautifulsoup中,方法'findAll'已重命名为'找到所有'。 链接到官方文档
因此,答案将是
soup.find_all("html_element", class_="your_class_name")
overlord answered 2019-02-15T20:13:43Z
14 votes
具体到BeautifulSoup 3:
soup.findAll('div',
{'class': lambda x: x
and 'stylelistrow' in x.split()
}
)
将找到所有这些: