首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 更多程式設計知識

Python HTML 表格解析器實作

     編輯:更多程式設計知識

使用 libxml2dom 解析 HTML 表格,支援有無表頭兩種模式。

核心 API


def parse_tables(source, headers, table_index):
    """
    source: HTML 原始碼字串
    headers: 欲擷取的欄位索引(list of int)或表頭名稱(list of str)
    table_index: 第幾個 table (0-based)
    return: list of list,每內層列表為一列資料
    """

兩種模式

  • 無表頭模式:headers = [0, 2, 3] 擷取第 0、2、3 欄
  • 有表頭模式:headers = ['Name', 'Price'] 依 <th> 內容比對

關鍵解析邏輯


doc = libxml2dom.parseString(source, html=1)
tables = doc.getElementsByTagName('table')
main_table = tables[table_index]

if isinstance(headers[0], str):  # 有表頭
    ths = main_table.getElementsByTagName('th')
    header_idx = [i for i, th in enumerate(ths) if th.textContent in headers]
else:  # 無表頭
    header_idx = headers

rows = main_table.getElementsByTagName('tr')
for row in rows[1:]:  # 跳過表頭列
    cells = row.getElementsByTagName('td')
    yield [cells[i].textContent for i in header_idx]

依賴安裝


pip install libxml2dom
# 需系統安裝 libxml2

輕量級表格資料擷取工具,適合固定格式網頁資料抓取。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved