Reputation: 267190
Say I reference an element inside of a table in a HTML page like this:
someEl = soup.findAll(text = "some text")
I know for sure this element is embedded inside a table, is there a way to find the parent table without having to call .parent so many times?
<table...>
..
..
<tr>....<td><center><font..><b>some text</b></font></center></td>....<tr>
<table>
Upvotes: 3
Views: 3881
Reputation: 7997
Check out findParents
, it has a similar form to findAll
:
soup = BeautifulSoup("<table>...</table>")
for text in soup.findAll(text='some text')
table = text.findParents('table')[0]
# table is your now your most recent `<table>` parent
Here are the docs for findAllPrevious
and also findParents
.
Upvotes: 6
Reputation: 129099
while someEl.name != "table":
someEl = someEl.parent
# someEl is now the table
Upvotes: 1