views:

42

answers:

2

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>
+1  A: 
while someEl.name != "table":
    someEl = someEl.parent
# someEl is now the table
icktoofay
+2  A: 

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.

Jesse Dhillon