Skip to content

Instantly share code, notes, and snippets.

@panzi
Last active November 18, 2026 00:24
Show Gist options
  • Select an option

  • Save panzi/26ca5c17dbfeb484c07b0f5480751d10 to your computer and use it in GitHub Desktop.

Select an option

Save panzi/26ca5c17dbfeb484c07b0f5480751d10 to your computer and use it in GitHub Desktop.
Parse tables from HTML.
#!/usr/bin/env python3
import re
from typing import NamedTuple, Literal, TextIO
from html.parser import HTMLParser
from html import escape as h
_SPACES = re.compile(r'\s+')
_IGNORE_TAGS = frozenset((
'script', 'noscript', 'style', 'meta', 'link', 'head', 'map',
'template', 'colgroup', 'wbr', 'track', 'source', 'audio', 'video',
'frame', 'frameset', 'iframe', 'embed', 'object',
))
_SELF_CLOSING = frozenset((
'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input',
'link', 'meta', 'param', 'source', 'track', 'wbr',
))
# TODO: The logic around is more complicated than what I implemented.
_CLOSE_OPTIONAL = frozenset((
'p', 'li', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
))
# TODO: All block tags
_BLOCK_TAGS = frozenset((
'div', 'p', 'section', 'dl', 'dt', 'dd', 'main', 'blockquote', 'figcaption',
'header', 'nav', 'details', 'summary', 'textarea',
'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'table', 'tr',
))
__all__ = 'get_html_tables',
class TableCell(NamedTuple):
content: str
colspan: int = 1
rowspan: int = 1
class SimplifiedCell(NamedTuple):
content: str
row: int
column: int
rowspan: int = 1
colspan: int = 1
class Table:
__slots__ = 'body', 'head', 'foot', 'caption',
body: list[list[TableCell]]
head: list[list[TableCell]]
foot: list[list[TableCell]]
caption: str|None
def __init__(
self,
body: list[list[TableCell]]|None = None,
head: list[list[TableCell]]|None = None,
foot: list[list[TableCell]]|None = None,
caption: str|None = None
) -> None:
self.body = body if body is not None else []
self.head = head if head is not None else []
self.foot = foot if foot is not None else []
self.caption = caption
def simplify(self) -> list[list[SimplifiedCell]]:
# What if all cells in a row have a rowspan > 1, but it isn't the last row?
# Would that even be valid HTML? Chrome renders that in a broken way.
# I think we can just assume that *we* don't generate such HTML.
rows = [*self.head, *self.body, *self.foot]
result: list[list[SimplifiedCell]] = []
prev_row: list[SimplifiedCell]|None = None
row_index = 0
max_columns = 0
for input_row in rows:
row: list[SimplifiedCell] = []
result.append(row)
prev_row_size = 0 if prev_row is None else len(prev_row)
input_column_index = 0
while input_column_index < len(input_row):
column_index = len(row)
prev_cell = None if prev_row is None or column_index >= prev_row_size else prev_row[column_index]
if prev_cell is not None and prev_cell.row + prev_cell.rowspan > row_index:
row.append(prev_cell)
elif input_column_index < len(input_row):
input_cell = input_row[input_column_index]
cell = SimplifiedCell(input_cell.content, row_index, column_index, input_cell.rowspan, input_cell.colspan)
colspan = input_cell.colspan
for _ in range(colspan):
row.append(cell)
input_column_index += 1
column_index = len(row)
while column_index < prev_row_size:
prev_cell = prev_row[column_index] # type: ignore
if prev_cell.row + prev_cell.rowspan > row_index:
row.append(prev_cell)
column_index += 1
if len(row) > max_columns:
max_columns = len(row)
prev_row = row
row_index += 1
# Handle row spans at the end of the table.
# There shouldn't be any! It's not valid HTML.
if prev_row is not None:
max_row_span = 0
for cell in prev_row:
rowspan = cell.rowspan
if rowspan > max_row_span:
max_row_span = rowspan
for rowspan in range(1, max_row_span):
row: list[SimplifiedCell] = []
for prev_row_cell in prev_row:
row.append(
prev_row_cell if prev_row_cell.rowspan >= rowspan else
SimplifiedCell("", row_index, len(row))
)
# Padd all rows to same width.
for row_index in range(len(result)):
row = result[row_index]
while len(row) < max_columns:
row.append(SimplifiedCell("", row_index, len(row)))
return result
def to_html(self) -> str:
buf: list[str] = []
self._to_html(buf)
return ''.join(buf)
__str__ = to_html
def _to_html(self, buf: list[str]) -> None:
append = buf.append
append('<table>')
if (caption := self.caption) is not None:
append('<caption>')
append(h(caption))
append('</caption>')
def _append_rows(section_tag: str, cell_tag: str, rows: list[list[TableCell]]) -> None:
append('<')
append(section_tag)
append('>')
for row in rows:
append('<tr>')
for cell in row:
append('<')
append(cell_tag)
if (rowspan := cell.rowspan) > 1:
append(' rowspan="')
append(str(rowspan))
append('"')
if (colspan := cell.colspan) > 1:
append(' colspan="')
append(str(colspan))
append('"')
append('>')
first = True
for line in cell.content.split('\n'):
if first:
first = False
else:
append('<br>')
# TODO: handle other whitespace?
append(line)
append('</')
append(cell_tag)
append('>')
append('</tr>')
append('</')
append(section_tag)
append('>')
if rows := self.head:
_append_rows('thead', 'th', rows)
if rows := self.body:
_append_rows('tbody', 'td', rows)
if rows := self.foot:
_append_rows('tfoot', 'td', rows)
append('</table>')
def simplify_table(table: Table) -> list[list[str]]:
return [
[
# resolve spans
cell.content if cell.row == row_index and cell.column == column_index else ""
for column_index, cell in enumerate(row)
]
for row_index, row in enumerate(table.simplify())
]
class ParseState:
__slots__ = 'table', 'buf', 'row', 'section', 'colspan', 'rowspan', 'cell',
table: Table
buf: list[str]
colspan: int
rowspan: int
cell: Literal['td', 'th', 'caption']|None
section: list[list[TableCell]]|None
row: list[TableCell]|None
def __init__(self, table: Table) -> None:
self.table = table
self.buf = []
self.colspan = 0
self.rowspan = 0
self.cell = None
self.row = None
self.section = None
class TableParser(HTMLParser):
__slots__ = 'tables', '_parse_stack', '_ignore', '_pre', '_tag_stack', '_child_tag',
tables: list[Table]
_parse_stack: list[ParseState]
_ignore: int
_pre: int
_tag_stack: list[str]
_child_tag: str|None
def __init__(self, *, scripting: bool = False) -> None:
super().__init__(convert_charrefs=True, scripting=scripting)
self.tables = []
self._parse_stack = []
self._ignore = 0
self._pre = 0
self._tag_stack = []
self._child_tag = None
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
tagstack = self._tag_stack
if tagstack and (top := tagstack[-1]) in _CLOSE_OPTIONAL and tag in _CLOSE_OPTIONAL:
tagstack.pop()
self._handle_endtag(top)
tagstack.append(tag)
if self._ignore:
self._ignore += 1
elif tag in _IGNORE_TAGS:
self._ignore = 1
else:
match tag:
case 'table':
table = Table()
state = ParseState(table)
self._parse_stack.append(state)
self.tables.append(table)
case 'thead':
if self._parse_stack:
state = self._parse_stack[-1]
if state.section is None:
# else ignore illegal state
state.section = state.table.head
case 'tfoot':
if self._parse_stack:
state = self._parse_stack[-1]
if state.section is None:
# else ignore illegal state
state.section = state.table.foot
case 'tbody':
if self._parse_stack:
state = self._parse_stack[-1]
if state.section is None:
# else ignore illegal state
state.section = state.table.body
case 'tr':
if self._parse_stack:
state = self._parse_stack[-1]
if state.row is None:
# else ignore illegal state
section = state.table.body if state.section is None else state.section
row: list[TableCell] = []
section.append(row)
state.row = row
case 'td' | 'th':
if self._parse_stack:
state = self._parse_stack[-1]
if state.row is not None and state.cell is None:
# else ignore illegal state
colspan = 1
rowspan = 1
state.cell = tag
for attr_name, attr_value in attrs:
match attr_name:
case 'colspan':
if attr_value:
try:
value = int(attr_value, 10)
except ValueError:
pass
else:
if value > 0:
colspan = value
case 'rowspan':
if attr_value:
try:
value = int(attr_value, 10)
except ValueError:
pass
else:
if value > 0:
rowspan = value
state.colspan = colspan
state.rowspan = rowspan
for state in self._parse_stack[:-1]:
if state.cell is not None and state.row:
state.buf.append('\t')
case 'caption':
if self._parse_stack:
state = self._parse_stack[-1]
if state.row is not None and state.cell is None:
state.cell = 'caption'
case 'img':
alt: str|None = None
for attr_name, attr_value in attrs:
if attr_name == 'alt':
alt = attr_value
if alt:
self._append_text(alt)
case 'pre' | 'textarea':
self._pre += 1
self._child_tag = None
if tag in _SELF_CLOSING:
self._handle_endtag(tag)
def handle_endtag(self, tag: str) -> None:
tagstack = self._tag_stack
if tag in tagstack and tagstack[-1] != tag:
while (top := tagstack.pop()) != tag:
self._handle_endtag(top)
if tagstack:
tagstack.pop()
self._handle_endtag(tag)
def _handle_endtag(self, tag: str) -> None:
if self._ignore:
self._ignore -= 1
self._child_tag = tag
return
match tag:
case 'table':
if self._parse_stack:
self._parse_stack.pop()
self._block_end()
case 'thead':
if self._parse_stack:
state = self._parse_stack[-1]
if state.section is state.table.head:
state.section = None
case 'tfoot':
if self._parse_stack:
state = self._parse_stack[-1]
if state.section is state.table.foot:
state.section = None
case 'tbody':
if self._parse_stack:
state = self._parse_stack[-1]
if state.section is state.table.body:
state.section = None
case 'tr':
if self._parse_stack:
state = self._parse_stack[-1]
state.row = None
for state in self._parse_stack[:-1]:
if state.cell is not None:
state.buf.append('\n')
case 'td' | 'th':
if self._parse_stack:
state = self._parse_stack[-1]
if state.cell is not None:
if state.row is not None:
content = ''.join(state.buf)
if not self._pre:
content = content.rstrip()
state.row.append(TableCell(content, state.colspan, state.rowspan))
state.buf.clear()
state.cell = None
case 'caption':
if self._parse_stack:
state = self._parse_stack[-1]
if state.cell is not None:
content = ''.join(state.buf)
if not self._pre:
content = content.rstrip()
state.table.caption = content
case 'br' | 'dt' | 'li':
self._newline()
case 'hr':
for state in self._parse_stack:
if state.cell is not None:
state.buf.append('----\n')
case 'pre':
self._pre -= 1
self._block_end()
case _:
if tag in _BLOCK_TAGS and self._child_tag not in _BLOCK_TAGS:
self._block_end()
self._child_tag = tag
def _append_text(self, text: str) -> None:
if not text:
return
if self._pre:
for state in self._parse_stack:
if state.cell is not None:
state.buf.append(text)
else:
text = _SPACES.sub(' ', text)
text_lstrip = text.lstrip()
for state in self._parse_stack:
if state.cell is not None:
buf = state.buf
if not buf or buf[-1][-1].isspace():
if text_lstrip:
buf.append(text)
else:
buf.append(text)
def _block_end(self) -> None:
for state in self._parse_stack:
if state.cell is not None:
state.buf.append('\n\n')
def _newline(self) -> None:
for state in self._parse_stack:
if state.cell is not None:
state.buf.append('\n')
def handle_data(self, data: str) -> None:
self._append_text(data)
def get_html_tables(html: str) -> list[Table]:
parser = TableParser()
parser.feed(html)
return parser.tables
def main() -> None:
import sys
import csv
import argparse
ap = argparse.ArgumentParser()
ap.add_argument('-o', '--output', default=None)
ap.add_argument('files', nargs='+')
args = ap.parse_args()
output: str|None = args.output
files: list[str] = args.files
def _process(outfp: TextIO) -> None:
writer = csv.writer(outfp)
for filename in files:
with open(filename, 'r') as htmlfp:
html = htmlfp.read()
for table in get_html_tables(html):
rows = simplify_table(table)
writer.writerows(rows)
if output is None or output == '-':
_process(sys.stdout)
else:
with open(output, 'w') as outfp:
_process(outfp)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment