BeautifulSoup4: select items where attributes are not x

I would like to do something like this:

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

I want to find all td that do not have class foo.
Obviously this does not work, what does?

+7
python html html-parsing beautifulsoup
source share
1 answer

BeautifulSoup really makes the “soup” beautiful and easy to use.

You can pass a function to the attribute value:

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

Demo:

 >>> 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 
+15
source share

All Articles