2 # -*- coding: iso-8859-1 -*-
3 # Hello, this program is written in Python - http://python.org
4 programname = 'html2csv - version 2002-09-20 - http://sebsauvage.net'
6 import sys, getopt, os.path, glob, HTMLParser, re
8 try: import psyco ; psyco.jit() # If present, use psyco to accelerate the program
12 ''' Display program usage. '''
13 progname = os.path.split(progname)[1]
14 if os.path.splitext(progname)[1] in ['.py','.pyc']: progname = 'python '+progname
16 A coarse HTML tables to CSV (Comma-Separated Values) converter.
18 Syntax : %s source.html
20 Arguments : source.html is the HTML file you want to convert to CSV.
21 By default, the file will be converted to csv with the same
22 name and the csv extension (source.html -> source.csv)
25 Examples : %s mypage.html
28 This program is public domain.
29 Author : Sebastien SAUVAGE <sebsauvage at sebsauvage dot net>
31 ''' % (programname, progname, progname, progname)
33 class html2csv(HTMLParser.HTMLParser):
34 ''' A basic parser which converts HTML tables into CSV.
35 Feed HTML with feed(). Get CSV with getCSV(). (See example below.)
36 All tables in HTML will be converted to CSV (in the order they occur
38 You can process very large HTML files by feeding this class with chunks
39 of html while getting chunks of CSV by calling getCSV().
40 Should handle badly formated html (missing <tr>, </tr>, </td>,
41 extraneous </td>, </tr>...).
42 This parser uses HTMLParser from the HTMLParser module,
43 not HTMLParser from the htmllib module.
44 Example: parser = html2csv()
45 parser.feed( open('mypage.html','rb').read() )
46 open('mytables.csv','w+b').write( parser.getCSV() )
47 This class is public domain.
48 Author: Sébastien SAUVAGE <sebsauvage at sebsauvage dot net>
51 2002-09-19 : - First version
52 2002-09-20 : - now uses HTMLParser.HTMLParser instead of htmllib.HTMLParser.
53 - now parses command-line.
56 - convert html entities (&name; and &#ref;) to Ascii.
59 HTMLParser.HTMLParser.__init__(self)
60 self.CSV = '' # The CSV data
61 self.CSVrow = '' # The current CSV row beeing constructed from HTML
62 self.inTD = 0 # Used to track if we are inside or outside a <TD>...</TD> tag.
63 self.inTR = 0 # Used to track if we are inside or outside a <TR>...</TR> tag.
64 self.re_multiplespaces = re.compile('\s+') # regular expression used to remove spaces in excess
65 self.rowCount = 0 # CSV output line counter.
66 def handle_starttag(self, tag, attrs):
67 if tag == 'tr': self.start_tr()
68 elif tag == 'td': self.start_td()
69 def handle_endtag(self, tag):
70 if tag == 'tr': self.end_tr()
71 elif tag == 'td': self.end_td()
73 if self.inTR: self.end_tr() # <TR> implies </TR>
76 if self.inTD: self.end_td() # </TR> implies </TD>
78 if len(self.CSVrow) > 0:
79 self.CSV += self.CSVrow[:-1]
84 if not self.inTR: self.start_tr() # <TD> implies <TR>
91 def handle_data(self, data):
93 self.CSVrow += self.re_multiplespaces.sub(' ',data.replace('\t',' ').replace('\n','').replace('\r','').replace('"','""'))
94 def getCSV(self,purge=False):
96 If purge is true, getCSV() will return all remaining data,
97 even if <td> or <tr> are not properly closed.
98 (You would typically call getCSV with purge=True when you do not have
99 any more HTML to feed and you suspect dirty HTML (unclosed tags). '''
100 if purge and self.inTR: self.end_tr() # This will also end_td and append last CSV row to output CSV.
101 dataout = self.CSV[:]
106 if __name__ == "__main__":
107 try: # Put getopt in place for future usage.
108 opts, args = getopt.getopt(sys.argv[1:],None)
109 except getopt.GetoptError:
110 print usage(sys.argv[0]) # print help information and exit:
113 print usage(sys.argv[0]) # print help information and exit:
116 html_files = glob.glob(args[0])
117 for htmlfilename in html_files:
118 outputfilename = os.path.splitext(htmlfilename)[0]+'.csv'
120 print 'Reading %s, writing %s...' % (htmlfilename, outputfilename)
122 htmlfile = open(htmlfilename, 'rb')
123 csvfile = open( outputfilename, 'w+b')
124 data = htmlfile.read(8192)
127 csvfile.write( parser.getCSV() )
128 sys.stdout.write('%d CSV rows written.\r' % parser.rowCount)
129 data = htmlfile.read(8192)
130 csvfile.write( parser.getCSV(True) )
134 print 'Error converting %s ' % htmlfilename
135 try: htmlfile.close()