Python 2.7 用BeautifulSoup获取没有特定祖先的元素?

Python 2.7 用BeautifulSoup获取没有特定祖先的元素?,python-2.7,beautifulsoup,Python 2.7,Beautifulsoup,我的HTML包含如下内容: 别理我 抓住我 (这是一个简化的示例。) 使用beautifulsoup,如何获取没有类为ignore的祖先的span?您可以选择所有span元素,然后通过检查它们是否有类为ignore的父元素来过滤它们 在下面的示例中,.select()方法选择所有span元素,然后条件语句过滤掉.find\u parents()返回类为ignore的元素: for element in soup.select('span'): if not element.find_pa

我的HTML包含如下内容:


别理我
抓住我
(这是一个简化的示例。)


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

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

在下面的示例中,
.select()
方法选择所有span元素,然后条件语句过滤掉
.find\u 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)
如果您只想直接查看元素列表:

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