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 IDLE加上自动补全和历史功能
Nov 30 Python
Python实现简单的可逆加密程序实例
Mar 05 Python
详解python3中socket套接字的编码问题解决
Jul 01 Python
python实现决策树
Dec 21 Python
Python实现针对给定单链表删除指定节点的方法
Apr 12 Python
Python之pandas读写文件乱码的解决方法
Apr 20 Python
Python标准库使用OrderedDict类的实例讲解
Feb 14 Python
使用django和vue进行数据交互的方法步骤
Nov 11 Python
Python Opencv轮廓常用操作代码实例解析
Sep 01 Python
Python开发入门——迭代的基本使用
Sep 03 Python
Python 用__new__方法实现单例的操作
Dec 11 Python
Python爬虫自动化获取华图和粉笔网站的错题(推荐)
Jan 08 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
PHPWind9.0手动屏蔽验证码解决后台关闭验证码但是依然显示的问题
2016/08/12 PHP
PHP+Ajax无刷新带进度条图片上传示例
2017/02/08 PHP
laravel 实现向公共模板中传值 (view composer)
2019/10/22 PHP
使用jQuery实现的网页版的个人简历(可换肤)
2013/04/19 Javascript
jQuery Animation实现CSS3动画示例介绍
2013/08/14 Javascript
jQuery写fadeTo示例代码
2014/02/21 Javascript
微信支付如何实现内置浏览器的H5页面支付
2015/09/25 Javascript
JS组件中bootstrap multiselect两大组件较量
2016/01/26 Javascript
JavaScript 中有关数组对象的方法(详解)
2016/08/15 Javascript
js注入 黑客之路必备!
2016/09/14 Javascript
Vue.js实战之通过监听滚动事件实现动态锚点
2017/04/04 Javascript
AngularJS 支付倒计时功能实现思路
2017/06/05 Javascript
基于input框覆盖掉数字英文的实例讲解
2017/07/21 Javascript
在原生不支持的旧环境中添加兼容的Object.keys实现方法
2017/09/11 Javascript
react.js组件实现拖拽复制和可排序的示例代码
2018/08/20 Javascript
详解使用VUE搭建后台管理系统(vue-cli更新至3.0)
2018/08/22 Javascript
Element-ui之ElScrollBar组件滚动条的使用方法
2018/09/14 Javascript
angular4笔记系列之内置指令小结
2018/11/09 Javascript
Vue脚手架编写试卷页面功能
2020/03/17 Javascript
Python类的基础入门知识
2008/11/24 Python
python中类变量与成员变量的使用注意点总结
2017/04/29 Python
Anaconda下配置python+opencv+contribx的实例讲解
2018/08/06 Python
python3 中文乱码与默认编码格式设定方法
2018/10/31 Python
使用python根据端口号关闭进程的方法
2018/11/06 Python
ipython和python区别详解
2019/06/26 Python
python 模拟创建seafile 目录操作示例
2019/09/26 Python
Keras设定GPU使用内存大小方式(Tensorflow backend)
2020/05/22 Python
如何用python处理excel表格
2020/06/09 Python
Python Pandas list列表数据列拆分成多行的方法实现
2020/12/14 Python
expedia比利时:预订航班+酒店并省钱
2018/07/13 全球购物
JSP和Servlet有哪些相同点和不同点,他们之间的联系是什么?
2015/10/22 面试题
2014年服务员个人工作总结
2014/12/23 职场文书
85句关于理想的名言警句大全
2019/08/22 职场文书
销区经理年终述职报告模板
2019/11/28 职场文书
Apache Calcite 实现方言转换的代码
2021/04/24 Servers
openstack云计算keystone组件工作介绍
2022/04/20 Servers