gpt4 book ai didi

python - 使用Python按位置从html中提取表格

转载 作者:行者123 更新时间:2023-12-01 04:48:16 25 4
gpt4 key购买 nike

我想从包含多个表的html文档中提取特定的表,但不幸的是没有标识符。但是,有一个表格标题。我似乎无法弄清楚。

这是一个 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 或名称获取表,但我只需要一个只能按位置识别的表。

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

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

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

最佳答案

您可以依赖表格标题。

通过文本查找元素将函数作为 text argument 传递值,然后得到parent :

table_name = "TABLE 1" 

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

关于python - 使用Python按位置从html中提取表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28973684/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com