【发布时间】:2019-11-07 04:08:40
【问题描述】:
如何使用漂亮的汤从下面的 html 中提取两种表格类型的表格标题
<body>
<p>some other data 1</p>
<p>Table1 heading</p>
<div></div>
<div>
<div><table width="15%"><tbody>
<tr>
<td><p>data1_00</p></td>
<td><p>data1_01</p></td>
</tr>
<tr>
<td><p>data1_10</p></td>
<td><p>data1_11</p></td>
</tr>
</tbody></table></div>
</div>
<br><br>
<div>some other data 2</div>
<div>Table2 heading</div>
<div>
<div><table width="15%"><tbody>
<tr>
<td><p>data2_00</p></td>
<td><p>data2_01</p></td>
</tr>
<tr>
<td><p>data2_10</p></td>
<td><p>data2_11</p></td>
</tr>
</tbody></table></div>
</div>
</body>
在第一个表中,标题位于<p> 标签内,第二个表标题位于<div> 标签内。同样在第二张桌子上,桌子上方还有一个空白的<div> 标签。
如何提取两个表格标题?
目前我正在使用table.find_previous('div') 搜索当前表格上方的前一个<div>,其中的文本将保存为标题。
from bs4 import BeautifulSoup
import urllib.request
htmlpage = urllib.request.urlopen(url)
page = BeautifulSoup(htmlpage, "html.parser")
all_divtables = page.find_all('table')
for table in all_divtables:
curr_div = table
while True:
curr_div = curr_div.find_previous('div')
if len(curr_div.find_all('table')) > 0:
continue
else:
heading = curr_div.text.strip()
print(heading)
break
想要的输出:
Table1 headingTable2 heading
【问题讨论】:
-
你能贴出你的python代码吗?
-
@Wonka,添加代码
-
您现在可以发布您想要的输出吗? find_all("tr") 似乎更好,我会等待你想要的输出知道你想要什么。
-
检查@Andrej Kesely 的答案,这似乎是一个不错的解决方案。
标签: python html python-3.x beautifulsoup scrapy