In BeautifulSoup there isn’t a built-in one-liner called closest() like the DOM’s element.closest(".group"), but you can get exactly the same behavior by walking up the .parents generator (or by using BS4’s find_parent) and testing each ancestor against your selector.
1) Using find_parent
If you know the tag name and/or the class you’re looking for, you can simply do
from bs4 import BeautifulSoup
html = """
<div class="group" id="outer">
<section>
<div>
<p id="foo">Hello</p>
</div>
</section>
</div>
"""
soup = BeautifulSoup(html, "html.parser")
p = soup.find("p", id="foo")
# nearest <div class="group"> above <p>
group_div = p.find_parent("div", class_="group")
print(group_div["id"]) # → "outer"
find_parent() returns the first matching parent (i.e. the nearest).
2) Generic CSS selector via SoupSieve
Since BeautifulSoup 4.7.0, CSS selectors are powered by [SoupSieve]. You can use SoupSieve’s match() to test each ancestor against any selector:
import soupsieve as sv
from bs4 import BeautifulSoup
html = """… same as above …"""
soup = BeautifulSoup(html, "html.parser")
p = soup.select_one("p#foo")
def closest(el, selector):
"""
Walks up from el (but not including el itself) until
an ancestor matches the CSS selector.
"""
for parent in el.parents:
if sv.match(parent, selector):
return parent
return None
group = closest(p, ".group")
print(group) # <div class="group" id="outer">…</div>
print(group["id"]) # outer
If you do want to allow the element itself to match, just start the loop with for parent in (el, *el.parents): ….
3) A little helper you can drop into your code
import soupsieve as sv
def bs_closest(el, selector, include_self=False):
"""
Mimics Element.closest() in the browser.
- selector: any CSS selector SoupSieve understands
- include_self: if True, test el itself first
"""
ancestors = el.parents
if include_self:
ancestors = [el] + list(ancestors)
for anc in ancestors:
if sv.match(anc, selector):
return anc
return None
# usage:
group = bs_closest(p, ".group", include_self=False)
Summary
- If it’s just a tag/class lookup, use
element.find_parent(name, class_=…).
- For arbitrary CSS selectors, iterate
element.parents and call soupsieve.match(parent, selector).
- Wrap that in a helper to get a true “closest” helper.
That’s it! 🎉