我的HTML包含以下内容:
<div class="ignore">
<span>ignore me</span>
</div>
<span>get me</span>
(这是一个简化的例子。)
使用beautifulsoup,如何获取没有类span
的祖先的ignore
?
答案 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)