【发布时间】:2012-04-04 17:31:01
【问题描述】:
我想使用 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>
【问题讨论】:
标签: python screen-scraping beautifulsoup