网络编程
位置:首页>> 网络编程>> Python编程>> python实现将html表格转换成CSV文件的方法

python实现将html表格转换成CSV文件的方法

作者:秋风秋雨  发布时间:2023-08-25 00:48:41 

标签:python,html,CSV

本文实例讲述了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: Sébastien 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 &#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 <TD>...</TD> tag.
   self.inTR = 0   # Used to track if we are inside or outside a <TR>...</TR> 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() # <TR> implies </TR>
   self.inTR = 1
 def end_tr(self):
   if self.inTD: self.end_td() # </TR> implies </TD>
   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() # <TD> implies <TR>
   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 <td> or <tr> 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程序设计有所帮助。

0
投稿

猜你喜欢

  • 一提起Google的产品,大多数人可能都会想到用一个词来形容,“简洁”。简单得来又实用,这就是Google的产品设计方针了。Jon Wile
  • 网站改版,如何改?如果只是设计、功能和栏目等的稍微变动,这些很简单,从技术 上说并没有多少难度。只是对于网站本身的发展来说,没有多大的作用,
  • 本文实例讲述了Python实现读取txt文件中的数据并绘制出图形操作。分享给大家供大家参考,具体如下:下面的是某一文本文件中的数据。6.11
  • 一、前言很多时候,我们都有远程控制电脑的需求。比如正在下载某样东西,需要让电脑在下载完后关机。或者你需要监控一个程序的运行状况等。今天我们就
  • 下面这些命令可以在命令行下用isql执行,isql -E -Q "命令",isql.exe
  • 一、数据类型分类1、按存值个数区分单个值:数字,字符串多个值(容器):列表,元组,字典,集合2、按可变不可变区分可变:列表[],字典{},集
  • 动态联接库(DLL)是加快应用程序关键部分的执行速度的重要方法,但有一点恐怕大部分人都不知道,那就是在ASP文件也能通过调用DLL来加快服务
  • 这篇文章主要介绍了如何使用python实现模拟鼠标点击,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋
  • 第一步:登陆root用户。第二步:新建一个数据表,并且选好排序规则,此处我使用testtable。第三步:我们新建一个用户输入相关的账户名以
  • <script> Function.prototype.$bind=function(object) {   
  • 方法如下: response.cookies(cookiesname)[(key)|.attribute]=value 解释如下:cooki
  • 文章先介绍了关于俄罗斯方块游戏的几个术语。边框——由10*20个空格组成,方块就落在这里面。盒子——组成方块的其中小方块,是组成方块的基本单
  • 关于python 性能提升的一些方案。一、函数调用优化(空间跨度,避免访问内存) 程序的优化核心点在于尽量减少操作跨度,包括代码执
  • 大家在使用ASP设计用户提交表单的时候,如果涉及到网址输入框,那么相信都有可能会用到这个效果,使用正则表达式验证网址合法性。代码如下:<
  • ⛳️ 本次反反爬实战案例背景本篇博客选择的案例是由 VX 好友提出,他希望有一篇博客能简单的介绍清楚下面这个问题。快速定位加密参数逻辑,快速
  • 1.核心代码使用py2neo连接neo4j的方法:from py2neo import Graphgraph = Graph("h
  • 读《论语》,子张十九,子夏曰:博学而笃志,切问而近思,仁在其中矣。 博学:架构需要广度,要尽量多学习各方面的知识。笃志:除了广度,架构师还需
  • 上段时间,团队内部有过好几次几次给力的分享,这里对西风师傅分享的继承机制稍作整理一下,适当加了写口语化的描述,留作备案。一、讲个故事吧澄清在
  • 在用wordpress这个博客的时候,我很奇怪的发现,最近写的内容排在第一页,而最早写的成了最后页。这显然有悖逻辑,正常的情况应该是最早写的
  • 本文实例为大家分享了PHP变量传值赋值和引用赋值变量销毁的具体代码,供大家参考,具体内容如下<?php   $a = 100
手机版 网络编程 asp之家 www.aspxhome.com