Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用BeautifulSoup查找html中的所有表_Python_Screen Scraping_Beautifulsoup - Fatal编程技术网

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

我想使用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()
从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>