使用BeautifulSoup查找html中的所有表

2024-04-28 22:17:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用BeautifulSoup找到html中的所有表。内表应包含在外表中。

我已经创建了一些有效的代码,它给出了预期的输出。但是,我不喜欢这个解决方案,因为它破坏了“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()

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

Tags: divinputbstitlehtmltableheadsoup
1条回答
网友
1楼 · 发布于 2024-04-28 22:17:12

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

没有什么会被摧毁。

相关问题 更多 >