BeautifulSoup4:选择属性不等于x的元素 [英] BeautifulSoup4: select elements where attributes are not equal to x

查看:55
本文介绍了BeautifulSoup4:选择属性不等于x的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做这样的事情:

soup.find_all('td', attrs!={"class":"foo"})

我想找到所有没有foo类的td.
显然上述方法不起作用,怎么办?

I want to find all td that do not have the class of foo.
Obviously the above doesn't work, what does?

推荐答案

BeautifulSoup 确实使汤"漂亮且易于使用.

BeautifulSoup really makes the "soup" beautiful and easy to work with.

可以在属性值中传递函数:

soup.find_all('td', class_=lambda x: x != 'foo')

演示:

>>> from bs4 import BeautifulSoup
>>> data = """
... <tr>
...     <td>1</td>
...     <td class="foo">2</td>
...     <td class="bar">3</td>
... </tr>
... """
>>> soup = BeautifulSoup(data)
>>> for element in soup.find_all('td', class_=lambda x: x != 'foo'):
...     print element.text
... 
1
3

这篇关于BeautifulSoup4:选择属性不等于x的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆