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实现百度关键词排名查询
Mar 30 Python
python刷投票的脚本实现代码
Nov 08 Python
举例详解Python中循环语句的嵌套使用
May 14 Python
Python导出DBF文件到Excel的方法
Jul 25 Python
Python开发之快速搭建自动回复微信公众号功能
Apr 22 Python
在Python中实现替换字符串中的子串的示例
Oct 31 Python
python实现求特征选择的信息增益
Dec 18 Python
使用CodeMirror实现Python3在线编辑器的示例代码
Jan 14 Python
Python嵌套式数据结构实例浅析
Mar 05 Python
浅析Python 中几种字符串格式化方法及其比较
Jul 02 Python
Python基础之数据结构详解
Apr 28 Python
C3 线性化算法与 MRO之Python中的多继承
Oct 05 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使用pear自带的mail类库发邮件的方法
2015/07/08 PHP
PHP中使用foreach()遍历二维数组的简单实例
2016/06/13 PHP
php实现的错误处理封装类实例
2017/06/20 PHP
jquery each的几种常用的使用方法示例
2014/01/21 Javascript
javascript的正则匹配方法学习
2016/02/24 Javascript
Dropzone.js实现文件拖拽上传功能(附源码下载)
2016/11/22 Javascript
Vue获取DOM元素样式和样式更改示例
2017/03/07 Javascript
Express+Nodejs 下的登录拦截实现代码
2017/07/01 NodeJs
关于JavaScript中的this指向问题总结篇
2017/07/23 Javascript
vue+iview动态渲染表格详解
2019/03/19 Javascript
Vuex的实战使用详解
2019/10/31 Javascript
vue 实现v-for循环回来的数据动态绑定id
2019/11/07 Javascript
vue element自定义表单验证请求后端接口验证
2019/12/11 Javascript
一篇文章让你搞懂JavaScript 原型和原型链
2020/11/23 Javascript
[01:01:29]2018DOTA2亚洲邀请赛 4.4 淘汰赛 VP vs Liquid 第一场
2018/04/05 DOTA
Python编码爬坑指南(必看)
2016/06/10 Python
Python中使用platform模块获取系统信息的用法教程
2016/07/08 Python
python实现的正则表达式功能入门教程【经典】
2017/06/05 Python
sublime python3 输入换行不结束的方法
2018/04/19 Python
Python pandas.DataFrame 找出有空值的行
2019/09/09 Python
Python数据可视化:幂律分布实例详解
2019/12/07 Python
python实现同一局域网下传输图片
2020/03/20 Python
python实现简单文件读写函数
2021/02/25 Python
css3学习心得分享
2013/08/19 HTML / CSS
HTML5 新旧语法标记对我们有什么好处
2012/12/13 HTML / CSS
大女孩胸罩:Big Girls Bras
2016/12/15 全球购物
用C#语言写出在本地创建一个UDP接收端口的具体过程
2016/02/22 面试题
什么是makefile? 如何编写makefile?
2013/01/02 面试题
幼师岗位求职简历的自荐信格式
2013/09/21 职场文书
银行实习鉴定
2013/12/13 职场文书
高中家长寄语
2014/04/02 职场文书
英语系本科生求职信
2014/07/15 职场文书
考试作弊检讨
2015/01/27 职场文书
助学金申请书该怎么写?
2019/07/16 职场文书
创业计划书之便利店
2019/09/05 职场文书
导游词之无锡丝业博物馆
2019/11/12 职场文书