使用 libxml2dom 解析 HTML 表格,支援有無表頭兩種模式。
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
輕量級表格資料擷取工具,適合固定格式網頁資料抓取。