使用python解析/提取表格数据 [英] Parse/extract table data using python

查看:774
本文介绍了使用python解析/提取表格数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 < HTML> 
< table border =1px>
< tr>
< td>是< / td>
< td> no< / td>
< / tr>
< / table>
< / html>

除了beautifulsoup之外,还有什么办法可以获得表格的内容吗(yes,no)?



一个python初学者,任何帮助或任何一种方向都会有很大的帮助。



谢谢

您可以使用Python标准库附带的 HTMLParser 模块。

 >>> import HTMLParser 
>>> data ='''
...< html>
...< table border =1px>
...< tr>
...< td>是< / td>
...< td> no< / td>
...< / tr>
...< / table>
...< / html>
...'''
>>> class TableParser(HTMLParser.HTMLParser):
... def __init __(self):
... HTMLParser.HTMLParser .__ init __(self)
... self.in_td = False
...
... def handle_starttag(self,tag,attrs):
... if tag =='td':
... self.in_td = True
...
... def handle_data(self,data):
... if self.in_td:
...打印数据
...
... def handle_endtag(self,tag):
... self.in_td = False
...
>>> p = TableParser()
>>> p.feed(data)
yes
no


<html> 
<table border="1px"> 
<tr>
<td>yes</td>
<td>no</td>
</tr>
</table>
</html>

Is there any way to get the contents of the table (yes ,no) besides beautifulsoup??

A python beginner,any help or any kind of direction will be of great help.

Thank you

解决方案

You can use the HTMLParser module that comes with the Python standard library.

>>> import HTMLParser
>>> data = '''
... <html> 
... <table border="1px"> 
... <tr>
... <td>yes</td>
... <td>no</td>
... </tr>
... </table>
... </html>
... '''
>>> class TableParser(HTMLParser.HTMLParser):
...     def __init__(self):
...         HTMLParser.HTMLParser.__init__(self)
...         self.in_td = False
...     
...     def handle_starttag(self, tag, attrs):
...         if tag == 'td':
...             self.in_td = True
...     
...     def handle_data(self, data):
...         if self.in_td:
...             print data
...     
...     def handle_endtag(self, tag):
...         self.in_td = False
... 
>>> p = TableParser()
>>> p.feed(data)
yes
no

这篇关于使用python解析/提取表格数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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