gpt4 book ai didi

python - 使用 BeautifulSoup 在 html 中查找所有表格

转载 作者:太空狗 更新时间:2023-10-29 21:22:49 27 4
gpt4 key购买 nike

我想使用 BeautifulSoup 在 html 中查找所有表格。内部表应包含在外部表中。

我已经创建了一些有效的代码,它给出了预期的输出。但是,我不喜欢这个解决方案,因为它使用 .decompose() 来破坏'soup'对象。

你知道如何以更优雅的方式做到这一点吗?

from BeautifulSoup import BeautifulSoup as bs

input = '''<html><head><title>title</title></head>
<body>
<p>paragraph</p>
<div><div>
<table>table1<table>inner11<table>inner12</table></table></table>
<div><table>table2<table>inner2</table></table></div>
</div></div>
<table>table3<table>inner3</table></table>
<table>table4<table>inner4</table></table>
</html>'''

soup = bs(input)
while(True):
t=soup.find("table")
if t is None:
break
print str(t)
t.decompose()

输出:

<table>table1<table>inner11<table>inner12</table></table></table>
<table>table2<table>inner2</table></table>
<table>table3<table>inner3</table></table>
<table>table4<table>inner4</table></table>

最佳答案

使用 soup.findAll("table") 代替 find()decompose() :

tables = soup.findAll("table")

for table in tables:
if table.findParent("table") is None:
print str(table)

输出:

<table>table1<table>inner11<table>inner12</table></table></table>
<table>table2<table>inner2</table></table>
<table>table3<table>inner3</table></table>
<table>table4<table>inner4</table></table>

没有任何东西被破坏/毁坏。

关于python - 使用 BeautifulSoup 在 html 中查找所有表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9783579/

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