【问题标题】:BeautifulSoup4: select elements where attributes are not equal to xBeautifulSoup4:选择属性不等于 x 的元素
【发布时间】:2014-07-10 23:22:04
【问题描述】:

我想做这样的事情:

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

我想找到所有不属于 foo 类的 td。
显然以上都行不通,怎么办?

【问题讨论】:

  • @alecxe 是的,谢谢。

标签: python html python-2.7 beautifulsoup html-parsing


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    有一个方法 .select() 允许你将 CSS 选择器作为字符串传递:

    soup.select('td:not(.foo)')
    

    上面的代码将返回所有不属于foo类的&lt;td&gt;标签。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-04
      • 2019-10-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多