user44796
user44796

Reputation: 1219

extract table from html by position using Python

I want to extract a specific table from an html document that contains mutliple tables, but unfortunately there are no identifiers. There is a table title, however. I just can't seem to figure it out.

Here is an example html file

<BODY>
<TABLE>
<TH>
<H3>    <BR>TABLE 1    </H3>
</TH>
<TR>
<TD>Data 1    </TD>
<TD>Data 2    </TD>
</TR>
<TR>
<TD>Data 3    </TD>
<TD>Data 4    </TD>
</TR>
<TR>
<TD>Data 5    </TD>
<TD>Data 6    </TD>
</TR>
</TABLE>

<TABLE>
<TH>
<H3>    <BR>TABLE 2    </H3>
</TH>
<TR>
<TD>Data 7    </TD>
<TD>Data 8    </TD>
</TR>
<TR>
<TD>Data 9    </TD>
<TD>Data 10    </TD>
</TR>
<TR>
<TD>Data 11    </TD>
<TD>Data 12    </TD>
</TR>
</TABLE>
</BODY>

I can use beautifulSoup 4 to get tables by id or name, but I need just a single table that is only identifiable by position.

I know that I can get the first table with:

tmp = f.read()
soup = BeautifulSoup(tmp) ## make it readable
table = soup.find('table') ### gets first table

but how would I get the second table?

Upvotes: 1

Views: 601

Answers (2)

exhoosier10
exhoosier10

Reputation: 121

If it's only identifiable by position, meaning it's always the 2nd table in the website, you could do:

tmp = f.read()
soup = BeautifulSoup(tmp)

# this will return the second table from the website
all_tables = soup.find_all('table')
second_table = all_tables[1]

Upvotes: 0

alecxe
alecxe

Reputation: 473763

You can rely on the table title.

Find the element by text passing a function as a text argument value, then get the parent:

table_name = "TABLE 1" 

table = soup.find(text=lambda x: x and table_name in x).find_parent('table')

Upvotes: 2

Related Questions