2 # -*- coding: iso-8859-1 -*-
3 # Hello, this program is written in Python - http://python.org
4 programname = 'html2tsv - 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 TSV (Tab-Separated Values) converter.
18 Syntax : %s source.html
20 Arguments : source.html is the HTML file you want to convert to TSV.
21 By default, the file will be converted to tsv with the same
22 name and the tsv extension (source.html -> source.tsv)
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 html2tsv(HTMLParser.HTMLParser):
34 ''' A basic parser which converts HTML tables into TSV.
35 Feed HTML with feed(). Get TSV with getTSV(). (See example below.)
36 All tables in HTML will be converted to TSV (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 TSV by calling getTSV().
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 = html2tsv()
45 parser.feed( open('mypage.html','rb').read() )
46 open('mytables.tsv','w+b').write( parser.getTSV() )
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.TSV = '' # The TSV data
61 self.TSVrow = '' # The current TSV 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 # TSV 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.TSVrow) > 0:
79 self.TSV += self.TSVrow[:-1]
84 if not self.inTR: self.start_tr() # <TD> implies <TR>
91 def handle_data(self, data):
93 self.TSVrow += self.re_multiplespaces.sub(' ',data.replace('\t',' ').replace('\n','').replace('\r','').replace('"','""'))
94 def getTSV(self,purge=False):
96 If purge is true, getTSV() will return all remaining data,
97 even if <td> or <tr> are not properly closed.
98 (You would typically call getTSV 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 TSV row to output TSV.
101 dataout = self.TSV[:]
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]+'.tsv'
120 print 'Reading %s, writing %s...' % (htmlfilename, outputfilename)
122 htmlfile = open(htmlfilename, 'rb')
123 tsvfile = open( outputfilename, 'w+b')
124 data = htmlfile.read(8192)
127 tsvfile.write( parser.getTSV() )
128 sys.stdout.write('%d TSV rows written.\r' % parser.rowCount)
129 data = htmlfile.read(8192)
130 tsvfile.write( parser.getTSV(True) )
134 print 'Error converting %s ' % htmlfilename
135 try: htmlfile.close()