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字典基本操作实例分析
Jul 11 Python
Python两个内置函数 locals 和globals(学习笔记)
Aug 28 Python
python字典多键值及重复键值的使用方法(详解)
Oct 31 Python
Python机器学习之决策树算法
Dec 22 Python
python之文件读取一行一行的方法
Jul 12 Python
python利用requests库模拟post请求时json的使用教程
Dec 07 Python
python框架django项目部署相关知识详解
Nov 04 Python
python实现局域网内实时通信代码
Dec 22 Python
python logging通过json文件配置的步骤
Apr 27 Python
python实现npy格式文件转换为txt文件操作
Jul 01 Python
详解pytorch tensor和ndarray转换相关总结
Sep 03 Python
Python移位密码、仿射变换解密实例代码
Jun 27 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 file_exists问题杂谈
2012/05/07 PHP
php中get_headers函数的作用及用法的详细介绍
2013/04/27 PHP
深入phpMyAdmin的安装与配置的详细步骤
2013/05/07 PHP
php字符串截取的简单方法
2013/07/04 PHP
PHP输出缓存ob系列函数详解
2014/03/11 PHP
php5.4以下版本json不支持不转义内容中文的解决方法
2015/01/13 PHP
PHP 将数组打乱 shuffle函数的用法及简单实例
2016/06/17 PHP
PHP封装的验证码工具类定义与用法示例
2018/08/22 PHP
关于hashchangebroker和statehashable的补充文档
2011/08/08 Javascript
JavaScript 验证码的实例代码(附效果图)
2013/03/22 Javascript
js从10种颜色中随机取色实现每次取出不同的颜色
2013/10/23 Javascript
jquery操作复选框(checkbox)的12个小技巧总结
2014/02/04 Javascript
js和css写一个可以自动隐藏的悬浮框
2014/03/05 Javascript
html文档中的location对象属性理解及常见的用法
2014/08/13 Javascript
jQuery中:disabled选择器用法实例
2015/01/04 Javascript
极力推荐一款小巧玲珑的可视化编辑器bootstrap-wysiwyg
2016/05/27 Javascript
轻松掌握JavaScript中介者模式
2016/08/26 Javascript
AngularJS 教程及实例代码
2017/10/23 Javascript
vue中的面包屑导航组件实例代码
2019/07/01 Javascript
带你使用webpack快速构建web项目的方法
2020/11/12 Javascript
python使用ddt过程中遇到的问题及解决方案【推荐】
2018/10/29 Python
django 实现celery动态设置周期任务执行时间
2019/11/19 Python
关于windows下Tensorflow和pytorch安装教程
2020/02/04 Python
表达自我的市场:Society6
2018/08/01 全球购物
广州一家公司的.NET面试题
2016/06/11 面试题
高中生自我鉴定范文
2013/10/30 职场文书
店长岗位职责
2013/11/21 职场文书
恐龙的灭绝教学反思
2014/02/12 职场文书
房产委托公证书
2014/04/08 职场文书
小学课外活动总结
2014/07/09 职场文书
国家领导干部党的群众路线教育实践活动批评与自我批评材料
2014/09/23 职场文书
2014年最新版离婚协议书范本
2014/11/25 职场文书
怎样写家长意见
2015/06/04 职场文书
2015大学生暑期实习报告
2015/07/13 职场文书
学雷锋感言
2015/08/03 职场文书
解决numpy和torch数据类型转化的问题
2021/05/23 Python