使用BeautifulSoup获取没有某些祖先的元素?

时间:2017-01-31 21:58:22

标签: python-2.7 beautifulsoup

我的HTML包含以下内容:

<div class="ignore">
  <span>ignore me</span>
</div>
<span>get me</span>

(这是一个简化的例子。)

使用beautifulsoup,如何获取没有类span的祖先的ignore

1 个答案:

答案 0 :(得分:1)

您可以选择所有span元素,然后通过检查它们是否包含类ignore的父元素来过滤它们。

在下面的示例中,.select()方法选择所有span元素,然后条件语句过滤掉.find_parents()返回类ignore的元素的元素:

for element in soup.select('span'):
  if not element.find_parents(attrs={"class": "ignore"}):
    # This element doesn't have an ancestor with class 'ignore'
    print(element.text)

如果你只是想要直接(example here)的元素列表:

spans = [e for e in soup.select('span') if not e.find_parents(attrs={"class": "ignore"})]
for span in spans:
  print(span.text)