查找使用BeautifulSoup HTML中的所有表 [英] Find all tables in html using BeautifulSoup

查看:205
本文介绍了查找使用BeautifulSoup HTML中的所有表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想找到使用BeautifulSoup HTML中的所有表。内蒙古表应包括在外部表。

我已经创造了一些code这工作,它给期望的输出。但是,我不喜欢这样的解决方案,因为它破坏了'汤'对象。

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

 从BeautifulSoup进口BeautifulSoup作为BS输入='''< HTML和GT;< HEAD><标题>标题< /标题>< /头>
<身体GT;
&所述p为H.;段&下; / P>
< D​​IV>< D​​IV>
    <table>table1<table>inner11<table>inner12</table></table></table>
    &LT; D​​IV&GT;&LT;表&gt;&表2 LT;表&gt;&inner2 LT; /表&gt;&LT; /表&gt;&LT; / DIV&GT;
&LT; / DIV&GT;&LT; / DIV&GT;
&LT;表&gt;&表3 LT;表&gt;&inner3 LT; /表&gt;&LT; /表&gt;
&LT;表&gt;&表4 LT;表&gt;&inner4 LT; /表&gt;&LT; /表&gt;
&LT; / HTML&GT;'''汤= BS(输入)
而(真):
    T = soup.find(表)
    如果t为无:
        打破
    打印STR(T)
    t.decompose()输出:
<table>table1<table>inner11<table>inner12</table></table></table>
&LT;表&gt;&表2 LT;表&gt;&inner2 LT; /表&gt;&LT; /表&gt;
&LT;表&gt;&表3 LT;表&gt;&inner3 LT; /表&gt;&LT; /表&gt;
&LT;表&gt;&表4 LT;表&gt;&inner4 LT; /表&gt;&LT; /表&gt;


解决方案

使用 soup.findAll(表)而不是找到() 分解()

 表= soup.findAll(表)在表表:
     如果table.findParent(表)是无:
         打印STR(表)

输出:

<$p$p><$c$c><table>table1<table>inner11<table>inner12</table></table></table>
&LT;表&gt;&表2 LT;表&gt;&inner2 LT; /表&gt;&LT; /表&gt;
&LT;表&gt;&表3 LT;表&gt;&inner3 LT; /表&gt;&LT; /表&gt;
&LT;表&gt;&表4 LT;表&gt;&inner4 LT; /表&gt;&LT; /表&gt;

和没有被摧毁/破坏。

I want to find all tables in html using BeautifulSoup. Inner tables should be included in outer tables.

I have created some code which works and it gives expected output. But, I don't like this solution, because it destroys 'soup' object.

Do you know how to do it in more elegant way ?

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> 

解决方案

use soup.findAll("table") instead of find() and decompose() :

tables = soup.findAll("table")

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

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>

and nothing gets destroyed/destructed.

这篇关于查找使用BeautifulSoup HTML中的所有表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆