【发布时间】:2014-07-10 23:22:04
【问题描述】:
我想做这样的事情:
soup.find_all('td', attrs!={"class":"foo"})
我想找到所有不属于 foo 类的 td。
显然以上都行不通,怎么办?
【问题讨论】:
-
@alecxe 是的,谢谢。
标签: python html python-2.7 beautifulsoup html-parsing
我想做这样的事情:
soup.find_all('td', attrs!={"class":"foo"})
我想找到所有不属于 foo 类的 td。
显然以上都行不通,怎么办?
【问题讨论】:
标签: python html python-2.7 beautifulsoup html-parsing
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
【讨论】:
有一个方法 .select() 允许你将 CSS 选择器作为字符串传递:
soup.select('td:not(.foo)')
上面的代码将返回所有不属于foo类的<td>标签。
【讨论】: