使用 Python 按位置从 html 中提取 table

extract table from html by position using Python

我想从包含多个 table 的 html 文档中提取特定的 table,但遗憾的是没有标识符。但是,有一个 table 标题。我就是想不通。

这里是一个例子html文件

<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>

我可以使用 beautifulSoup 4 通过 ID 或名称获取 tables,但我只需要一个只能按位置识别的 table。

我知道我可以通过以下方式获得第一个 table:

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

但是我如何获得第二个 table?

您可以信赖 table 标题。

通过文本 将函数作为 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')

如果它只能通过位置来识别,这意味着它在网站中始终是第 2 table,您可以这样做:

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]