python实现将html表格转换成CSV文件的方法


Posted in Python onJune 28, 2015

本文实例讲述了python实现将html表格转换成CSV文件的方法。分享给大家供大家参考。具体如下:

使用方法:python html2csv.py *.html
这段代码使用了 HTMLParser 模块

#!/usr/bin/python
# -*- coding: iso-8859-1 -*-
# Hello, this program is written in Python - http://python.org
programname = 'html2csv - version 2002-09-20 - http://sebsauvage.net'
import sys, getopt, os.path, glob, HTMLParser, re
try:  import psyco ; psyco.jit() # If present, use psyco to accelerate the program
except: pass
def usage(progname):
  ''' Display program usage. '''
  progname = os.path.split(progname)[1]
  if os.path.splitext(progname)[1] in ['.py','.pyc']: progname = 'python '+progname
  return '''%s
A coarse HTML tables to CSV (Comma-Separated Values) converter.
Syntax  : %s source.html
Arguments : source.html is the HTML file you want to convert to CSV.
      By default, the file will be converted to csv with the same
      name and the csv extension (source.html -> source.csv)
      You can use * and ?.
Examples  : %s mypage.html
      : %s *.html
This program is public domain.
Author : Sebastien SAUVAGE <sebsauvage at sebsauvage dot net>
     http://sebsauvage.net
''' % (programname, progname, progname, progname)
class html2csv(HTMLParser.HTMLParser):
  ''' A basic parser which converts HTML tables into CSV.
    Feed HTML with feed(). Get CSV with getCSV(). (See example below.)
    All tables in HTML will be converted to CSV (in the order they occur
    in the HTML file).
    You can process very large HTML files by feeding this class with chunks
    of html while getting chunks of CSV by calling getCSV().
    Should handle badly formated html (missing <tr>, </tr>, </td>,
    extraneous </td>, </tr>...).
    This parser uses HTMLParser from the HTMLParser module,
    not HTMLParser from the htmllib module.
    Example: parser = html2csv()
         parser.feed( open('mypage.html','rb').read() )
         open('mytables.csv','w+b').write( parser.getCSV() )
    This class is public domain.
    Author: Sébastien SAUVAGE <sebsauvage at sebsauvage dot net>
        http://sebsauvage.net
    Versions:
      2002-09-19 : - First version
      2002-09-20 : - now uses HTMLParser.HTMLParser instead of htmllib.HTMLParser.
            - now parses command-line.
    To do:
      - handle <PRE> tags
      - convert html entities (&name; and &#ref;) to Ascii.
      '''
  def __init__(self):
    HTMLParser.HTMLParser.__init__(self)
    self.CSV = ''   # The CSV data
    self.CSVrow = ''  # The current CSV row beeing constructed from HTML
    self.inTD = 0   # Used to track if we are inside or outside a <TD>...</TD> tag.
    self.inTR = 0   # Used to track if we are inside or outside a <TR>...</TR> tag.
    self.re_multiplespaces = re.compile('\s+') # regular expression used to remove spaces in excess
    self.rowCount = 0 # CSV output line counter.
  def handle_starttag(self, tag, attrs):
    if  tag == 'tr': self.start_tr()
    elif tag == 'td': self.start_td()
  def handle_endtag(self, tag):
    if  tag == 'tr': self.end_tr()
    elif tag == 'td': self.end_td()     
  def start_tr(self):
    if self.inTR: self.end_tr() # <TR> implies </TR>
    self.inTR = 1
  def end_tr(self):
    if self.inTD: self.end_td() # </TR> implies </TD>
    self.inTR = 0      
    if len(self.CSVrow) > 0:
      self.CSV += self.CSVrow[:-1]
      self.CSVrow = ''
    self.CSV += '\n'
    self.rowCount += 1
  def start_td(self):
    if not self.inTR: self.start_tr() # <TD> implies <TR>
    self.CSVrow += '"'
    self.inTD = 1
  def end_td(self):
    if self.inTD:
      self.CSVrow += '",' 
      self.inTD = 0
  def handle_data(self, data):
    if self.inTD:
      self.CSVrow += self.re_multiplespaces.sub(' ',data.replace('\t',' ').replace('\n','').replace('\r','').replace('"','""'))
  def getCSV(self,purge=False):
    ''' Get output CSV.
      If purge is true, getCSV() will return all remaining data,
      even if <td> or <tr> are not properly closed.
      (You would typically call getCSV with purge=True when you do not have
      any more HTML to feed and you suspect dirty HTML (unclosed tags). '''
    if purge and self.inTR: self.end_tr() # This will also end_td and append last CSV row to output CSV.
    dataout = self.CSV[:]
    self.CSV = ''
    return dataout
if __name__ == "__main__":
  try: # Put getopt in place for future usage.
    opts, args = getopt.getopt(sys.argv[1:],None)
  except getopt.GetoptError:
    print usage(sys.argv[0]) # print help information and exit:
    sys.exit(2)
  if len(args) == 0:
    print usage(sys.argv[0]) # print help information and exit:
    sys.exit(2)    
  print programname
  html_files = glob.glob(args[0])
  for htmlfilename in html_files:
    outputfilename = os.path.splitext(htmlfilename)[0]+'.csv'
    parser = html2csv()
    print 'Reading %s, writing %s...' % (htmlfilename, outputfilename)
    try:
      htmlfile = open(htmlfilename, 'rb')
      csvfile = open( outputfilename, 'w+b')
      data = htmlfile.read(8192)
      while data:
        parser.feed( data )
        csvfile.write( parser.getCSV() )
        sys.stdout.write('%d CSV rows written.\r' % parser.rowCount)
        data = htmlfile.read(8192)
      csvfile.write( parser.getCSV(True) )
      csvfile.close()
      htmlfile.close()
    except:
      print 'Error converting %s    ' % htmlfilename
      try:  htmlfile.close()
      except: pass
      try:  csvfile.close()
      except: pass
  print 'All done. '

希望本文所述对大家的Python程序设计有所帮助。

Python 相关文章推荐
Python中用Descriptor实现类级属性(Property)详解
Sep 18 Python
跟老齐学Python之复习if语句
Oct 02 Python
python对html代码进行escape编码的方法
May 04 Python
基于python脚本实现软件的注册功能(机器码+注册码机制)
Oct 09 Python
Python编程之黑板上排列组合,你舍得解开吗
Oct 30 Python
Python简单定义与使用二叉树示例
May 11 Python
Python3 SSH远程连接服务器的方法示例
Dec 29 Python
tensorflow 实现数据类型转换
Feb 17 Python
Python打印特殊符号及对应编码解析
May 07 Python
django queryset 去重 .distinct()说明
May 19 Python
Python flask框架实现查询数据库并显示数据
Jun 04 Python
用Python实现一个打字速度测试工具来测试你的手速
May 28 Python
python实现根据主机名字获得所有ip地址的方法
Jun 28 #Python
python自动zip压缩目录的方法
Jun 28 #Python
python查找指定具有相同内容文件的方法
Jun 28 #Python
python中getaddrinfo()基本用法实例分析
Jun 28 #Python
python实现搜索指定目录下文件及文件内搜索指定关键词的方法
Jun 28 #Python
分析用Python脚本关闭文件操作的机制
Jun 28 #Python
python实现linux下使用xcopy的方法
Jun 28 #Python
You might like
php中使用getimagesize获取图片、flash等文件的尺寸信息实例
2014/04/29 PHP
CI框架中$this-&gt;load-&gt;library()用法分析
2016/05/18 PHP
PHP实现网页内容html标签补全和过滤的方法小结【2种方法】
2017/04/27 PHP
PHP SFTP实现上传下载功能
2017/07/26 PHP
jQuery第三课 修改元素属性及内容的代码
2010/03/14 Javascript
Jquery效果大全之制作电脑健康体检得分特效附源码下载
2015/11/02 Javascript
基于jQuey实现鼠标滑过变色(整行变色)
2015/12/07 Javascript
JavaScript核心语法总结(推荐)
2016/06/02 Javascript
JavaScript中浅讲ajax图文详解
2016/11/11 Javascript
Ajax 加载数据 练习代码
2017/01/05 Javascript
Vue.js 2.0窥探之Virtual DOM到底是什么?
2017/02/10 Javascript
Vue项目中设置背景图片方法
2018/02/21 Javascript
Vue SSR 组件加载问题
2018/05/02 Javascript
Node 升级到最新稳定版的方法分享
2018/05/17 Javascript
JAVA面试题 static关键字详解
2019/07/16 Javascript
layui关闭层级、简单监听的实例
2019/09/06 Javascript
Python制作Windows系统服务
2017/03/25 Python
python列表生成式与列表生成器的使用
2018/02/23 Python
PIL图像处理模块paste方法简单使用详解
2019/07/17 Python
详解python statistics模块及函数用法
2019/10/27 Python
Python matplotlib以日期为x轴作图代码实例
2019/11/22 Python
Python matplotlib 绘制双Y轴曲线图的示例代码
2020/06/12 Python
Python实现Keras搭建神经网络训练分类模型教程
2020/06/12 Python
Pycharm安装第三方库失败解决方案
2020/11/17 Python
css3实现一个div设置多张背景图片及background-image属性实例演示
2017/08/10 HTML / CSS
美国婚礼装饰和活动用品批发供应商:Event Decor Direct
2018/10/12 全球购物
股份转让协议书
2014/04/12 职场文书
办公室文员岗位职责范本
2014/06/12 职场文书
国际金融专业自荐信
2014/07/05 职场文书
新郎结婚保证书
2015/02/26 职场文书
详解MySQL 用户权限管理
2021/04/20 MySQL
php实现自动生成验证码的实例讲解
2021/11/17 PHP
python数字类型和占位符详情
2022/03/13 Python
我去timi了,一起去timi是什么意思?
2022/04/13 杂记
我国拿下天问一号火星着陆区附近 22 个地理实体命名:平乐、西柏坡、古田、漠河等
2022/04/29 数码科技
SQL Server中的游标介绍
2022/05/20 SQL Server