本文实例讲述了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: Sebastien 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 &#
Copyright© 2013-2020
All Rights Reserved 京ICP备2023019179号-8