python soup findall 第几个元素_python - 如何按类查找元素

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'已重命名为'找到所有'。 链接到官方文档

cMifn.png

因此,答案将是

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()

}

)

将找到所有这些:

FlipMcF answered 2019-02-15T20:14:13Z

13 votes

一个直接的方式是:

soup = BeautifulSoup(sdata)

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

print each_div

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

Konark Modi answered 2019-02-15T20:14:42Z

6 votes

如何按类查找元素

我使用Beautifulsoup解析带有“class”属性的html元素时遇到问题。

你可以很容易地找到一个班级,但如果你想通过两个班级的交集来找到它,那就更难了,

从文档(重点添加):

如果要搜索与两个或更多CSS类匹配的标记,则应使用CSS选择器:

find_all

要清楚,这只选择了三角形和三角形的标签。

要查找一组类中的任何一个的交集(不是交集,而是联合),您可以给出find_all关键字参数的列表(从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重命名为更多Pythonic find_all。

Aaron Hall answered 2019-02-15T20:16:35Z

3 votes

尝试先检查div是否具有class属性,如下所示:

soup = BeautifulSoup(sdata)

mydivs = soup.findAll('div')

for div in mydivs:

if "class" in div:

if (div["class"]=="stylelistrow"):

print div

Mew answered 2019-02-15T20:16:59Z

3 votes

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

for hit in soup.findAll(name='span'):

print hit.contents[1]['class']

Stgltz answered 2019-02-15T20:17:22Z

1 votes

这对我有用:

for div in mydivs:

try:

clazz = div["class"]

except KeyError:

clazz = ""

if (clazz == "stylelistrow"):

print div

Larry Symms answered 2019-02-15T20:17:41Z

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值