本文实例讲述了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
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 , , ,
extraneous , …).
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
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 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 … tag.
self.intr = 0 # used to track if we are inside or outside a … 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() # implies
self.intr = 1
def end_tr(self):
if self.intd: self.end_td() # implies
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() # implies
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 or 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程序设计有所帮助。