草庐IT

python - BeautifulSoup4 : select elements where attributes are not equal to x

coder 2023-08-03 原文

我想做这样的事情:

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

我想找到所有没有 foo 类的 td。
显然上面的方法行不通,那行什么呢?

最佳答案

BeautifulSoup 确实使“汤”变得美观且易于使用。

can pass a function在属性值中:

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

关于python - BeautifulSoup4 : select elements where attributes are not equal to x,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23798062/

有关python - BeautifulSoup4 : select elements where attributes are not equal to x的更多相关文章

随机推荐