萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python HTML 表格轉 CSV 工具:基於 HTMLParser 的健壯解析器

功能特性

  • 解析 HTML 中所有 <table>,按順序輸出 CSV。
  • 容錯處理缺失 <tr>、</td> 等非標準標簽。
  • 支持流式處理:分塊餵入 HTML,分塊獲取 CSV。
  • 命令行批量轉換:python html2csv.py *.html。

核心解析器

from HTMLParser import HTMLParser
import re

class Html2Csv(HTMLParser):
    def __init__(self):
        HTMLParser.__init__(self)
        self.csv = ''
        self.row = ''
        self.in_td = 0
        self.in_tr = 0
        self.re_space = re.compile(r'\s+')

    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.in_tr: self._end_tr()
        self.in_tr = 1

    def _end_tr(self):
        if self.in_td: self._end_td()
        self.in_tr = 0
        if self.row:
            self.csv += self.row[:-1] + '\n'  # 去除尾隨逗號
            self.row = ''

    def _start_td(self):
        if not self.in_tr: self._start_tr()
        self.row += '"'
        self.in_td = 1

    def _end_td(self):
        if self.in_td:
            self.row += '",'
            self.in_td = 0

    def handle_data(self, data):
        if self.in_td:
            clean = self.re_space.sub(' ', data.replace('\t',' ').replace('\n','').replace('\r','').replace('"','""'))
            self.row += clean

    def get_csv(self, purge=False):
        if purge and self.in_tr: self._end_tr()
        out, self.csv = self.csv, ''
        return out

命令行入口

if __name__ == '__main__':
    import sys, glob
    for html_file in sys.argv[1:]:
        for f in glob.glob(html_file):
            parser = Html2Csv()
            parser.feed(open(f, 'rb').read())
            csv_data = parser.get_csv(purge=True)
            out_file = os.path.splitext(f)[0] + '.csv'
            open(out_file, 'wb').write(csv_data)
            print(f"Converted {f} -> {out_file}")

依賴

  • Python 2.x:標準庫 HTMLParser。
  • Python 3.x:from html.parser import HTMLParser。

注意

不處理嵌套表格、<pre> 標簽、HTML 實體解碼,如需完整功能建議使用 BeautifulSoup + pandas 方案。

copyright © 萬盛學電腦網 all rights reserved