針對含 <table> 的網頁,依指定欄位 (表頭文字或欄位索引) 提取資料,回傳列表的列表。
pip install libxml2dom
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 (每列被提取的欄位值)
"""
libxml2dom.parseString(source, html=1) 解析 DOMtable_index 個 <table>headers 為字串:掃描第一列 <th> 找對應欄位索引headers 為整數:直接作為欄位索引<tr>,提取對應 <td> 文字
html = '''Name Age Alice 30
'''
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