萬盛學電腦網

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

Python 解析 HTML 表格:基於 libxml2dom 的欄位提取工具

工具定位

針對含 <table> 的網頁,依指定欄位 (表頭文字或欄位索引) 提取資料,回傳列表的列表。

依賴安裝

pip install libxml2dom

核心 API


def parse_tables(source, headers, table_index=0):
    """
    source: HTML 字串 (可為整頁或單一 table)
    headers: list of str (表頭文字) 或 list of int (欄位索引)
    table_index: 第幾個 table (0-based)
    return: list of list (每列被提取的欄位值)
    """

運作邏輯

  1. 用 libxml2dom.parseString(source, html=1) 解析 DOM
  2. 取第 table_index 個 <table>
  3. 若 headers 為字串:掃描第一列 <th> 找對應欄位索引
  4. 若 headers 為整數:直接作為欄位索引
  5. 遍歷後續 <tr>,提取對應 <td> 文字
  6. 回傳二維列表

使用範例


html = '''
NameAge
Alice30
''' data = parse_tables(html, ['Name', 'Age']) # [['Alice', '30']] data2 = parse_tables(html, [0, 1]) # 同結果

完整程式碼結構 (節錄)


import libxml2dom

def parse_tables(source, headers, table_index):
    doc = libxml2dom.parseString(source, html=1)
    tables = doc.getElementsByTagName('table')
    if table_index >= len(tables):
        return []
    table = tables[table_index]
    rows = table.getElementsByTagName('tr')
    if not rows:
        return []
    # 判斷 headers 類型
    if isinstance(headers[0], int):
        return _parse_no_header(rows, headers)
    else:
        return _parse_with_header(rows, headers)

def _parse_with_header(rows, headers):
    header_row = rows[0]
    ths = header_row.getElementsByTagName('th')
    col_map = {}
    for idx, th in enumerate(ths):
        text = th.firstChild.data.strip() if th.firstChild else ''
        if text in headers:
            col_map[text] = idx
    # ... 提取資料列

注意事項

  • libxml2dom 需系統安裝 libxml2,Windows 較難部署
  • 現代專案建議改用 BeautifulSoup4 + lxml 或 pandas.read_html
  • 複雜表格 (合併儲存格、巢狀表格) 需更精細處理
copyright © 萬盛學電腦網 all rights reserved