BeautifulSoup4:选择属性不等于x的元素

kyl*_*lex 11 html python beautifulsoup html-parsing python-2.7

我想做这样的事情:

soup.find_all('td', attrs!={"class":"foo"})
Run Code Online (Sandbox Code Playgroud)

我想找到所有没有foo类的td.
显然以上不起作用,有什么作用?

ale*_*cxe 19

BeautifulSoup 真正使"汤"美丽,易于使用.

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

soup.find_all('td', class_=lambda x: x != 'foo')
Run Code Online (Sandbox Code Playgroud)

演示:

>>> 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
Run Code Online (Sandbox Code Playgroud)