Python 使用BeautifulSoup查找html中的所有表
我想使用BeautifulSoup查找html中的所有表。内部表格应包含在外部表格中 我已经创建了一些有效的代码,并给出了预期的输出。但是,我不喜欢这个解决方案,因为它使用了Python 使用BeautifulSoup查找html中的所有表,python,screen-scraping,beautifulsoup,Python,Screen Scraping,Beautifulsoup,我想使用BeautifulSoup查找html中的所有表。内部表格应包含在外部表格中 我已经创建了一些有效的代码,并给出了预期的输出。但是,我不喜欢这个解决方案,因为它使用了.decompose(),这会破坏“soup”对象 你知道如何用更优雅的方式做吗 from BeautifulSoup import BeautifulSoup as bs input = '''<html><head><title>title</title></hea
.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()
从BeautifulSoup导入BeautifulSoup作为bs
输入=''标题
段落
表1附件11附件12
表2附件2
表3.3
表4.4
'''
汤=bs(输入)
虽然(正确):
t=汤。查找(“表”)
如果t为无:
打破
打印str(t)
t、 分解
输出:
<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>
表1inner11 inner12
表2附件2
表3.3
表4.4
使用soup.findAll(“表格”)
而不是find()
和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>
表1inner11 inner12
表2附件2
表3.3
表4.4
没有什么会被破坏
<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>