Python implements the method of converting an HTML table to a CSV file

Source: Internet
Author: User
Tags dot net glob rowcount
The example in this article describes how Python implements the conversion of HTML tables to CSV files. Share to everyone for your reference. Specific as follows:

How to use: Python html2csv.py *.html
This code uses the Htmlparser module

#!/usr/bin/python#-*-coding:iso-8859-1-*-# Hello, this program was written in python-http://python.orgprogramname = ' html2csv-version 2002-09-20-http://sebsauvage.net ' Import sys, getopt, Os.path, Glob, Htmlparser, Retry:import Psyco ; Psyco.jit () # If present, use Psyco to accelerate the Programexcept:passdef usage (progname): "Display program usage. "' Progname = Os.path.split (Progname) [1] if Os.path.splitext (progname) [1] in ['. Py ', '. PYc ']: progname = ' python ' +progn Ame return '%sa coarse HTML tables to CSV (comma-separated Values) converter.      Syntax:%s source.htmlArguments:source.html is the HTML file, want to convert to CSV.       By default, the file is converted to CSV with the same name and the CSV extension (source.html-source.csv) can use * and?. Examples:%s mypage.html:%s *.htmlthis program was 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 is converted to CSV (in the order they occur in the HTML file). You can process very large HTML files by feeding the 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 and not htmlparser from the Htmllib module. Example:parser = Html2csv () parser.feed (open (' mypage.html ', ' RB '). Read ()) Open (' Mytables.csv ', ' w+b '). WRI    Te (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 in stead 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 ". CSV = "# The CSV data self. Csvrow = "# The current CSV row beeing constructed from HTML self.intd = 0 # Used-track if we is inside or out Side 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 Handl E_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 () #impliesSELF.INTR = 1 def end_tr (self): if SELF.INTD:SELF.END_TD () #impliesSELF.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 () #impliesSelf. 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 () would return all remaining data, even ifOr is not properly closed. (You would typically call Getcsv with Purge=true if you don't have any more HTML to feeds and you suspect dirty HTM L (unclosed tags).    "If Purge and Self.inTR:self.end_tr () # This would also END_TD and append last csv row to output CSV. Dataout = self. csv[:] Self.    CSV = ' return dataoutif __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 US   Age (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 () p Rint ' Reading%s, writing%s ... '% (Htmlfilename, outputfilename) try:htmlfile = open (Htmlfilename, ' RB ') CS Vfile = 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 (parse       R.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. '

Hopefully this article will help you with Python programming.

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.