Advanced · Web & APIs · Packages: standard library only
Project 23: HTML Table Scraper (html.parser)
Write an HTML table scraper with html.parser that handles captions, colspan, entities and line breaks, fetches a page from a local server and saves each table as CSV.
What you will learn
- Subclass HTMLParser and track state across tag events
- Handle colspan, entities and whitespace in cells
- Fetch a page with urllib from a local server
- Export tables to CSV and convert them to records
Prerequisites
- Classes and inheritance
- Lists of lists and dictionaries
- String methods (split, join, strip)
- The csv module
- Basic HTML: table, tr, th, td
Packages and installation
Packages: standard library only.
Project structure
scraper/
main.py
table1.csv (created when run)
table2.csv (created when run)Step-by-step build
- Prepare sample HTML. Keep a PAGE string with two tables. Serving it locally keeps the project offline.
- Subclass HTMLParser. Create TableParser with state: tables, current row, current cell and caption flag.
- Handle start tags. On table start a new table, on tr start a row, on td/th start a cell and read colspan.
- Handle data and end tags. Collect text pieces while inside a cell. On the end tag, clean the spaces and add the cell to the row.
- Support colspan. After a cell that spans N columns, add N-1 empty cells so rows stay aligned.
- Summarise. Print a padded table and the sum of every column in which all values are numbers.
- Save to CSV. csv.writer writes the rows. Use newline='' when opening the file.
- Fetch from the server. Start the local server on port 0, fetch the page with urllib, then shut down.
Complete source code
"""HTML Table Scraper: fetch a page from a local server and extract tables with html.parser."""
import csv
import threading
import urllib.request
from html.parser import HTMLParser
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
# A sample page we serve ourselves, so the project works offline.
PAGE = """<html><body>
<h1>Report</h1>
<table id="fruit"><caption>Fruit prices</caption>
<tr><th>Fruit</th><th>Price</th><th>Stock</th></tr>
<tr><td>Apple</td><td>1.20</td><td>40</td></tr>
<tr><td>Banana & Co</td><td>0.50</td><td>120</td></tr>
<tr><td>Cherry</td><td> 4.75 </td><td>8</td></tr>
</table>
<p>Some text between tables.</p>
<table id="team"><caption>Team</caption>
<tr><th>Name</th><th colspan="2">Contact</th></tr>
<tr><td>Ana</td><td>ana@example.com</td><td>555-0101</td></tr>
<tr><td>Ben<br>Smith</td><td colspan="2">no contact</td></tr>
</table>
</body></html>"""
class TableParser(HTMLParser):
"""Collects every table as {'caption': str, 'rows': [[cells]]}."""
def __init__(self):
super().__init__(convert_charrefs=True) # turns & into &
self.tables = []
self.row = None # current row (list) or None
self.cell = None # current cell text pieces or None
self.colspan = 1
self.in_caption = False
def handle_starttag(self, tag, attrs):
if tag == "table":
self.tables.append({"caption": "", "rows": []})
elif tag == "caption":
self.in_caption = True
elif tag == "tr" and self.tables:
self.row = []
elif tag in ("td", "th") and self.row is not None:
self.cell = []
try:
self.colspan = int(dict(attrs).get("colspan", 1))
except ValueError:
self.colspan = 1
elif tag == "br" and self.cell is not None:
self.cell.append(" ")
def handle_endtag(self, tag):
if tag == "caption":
self.in_caption = False
elif tag in ("td", "th") and self.cell is not None:
text = " ".join("".join(self.cell).split()) # trim and squeeze spaces
# A cell that spans 2 columns becomes the text plus empty fillers.
self.row.extend([text] + [""] * (self.colspan - 1))
self.cell = None
elif tag == "tr" and self.row is not None:
if self.row:
self.tables[-1]["rows"].append(self.row)
self.row = None
def handle_data(self, data):
if self.cell is not None:
self.cell.append(data)
elif self.in_caption:
self.tables[-1]["caption"] += data.strip()
def parse_tables(html):
parser = TableParser()
parser.feed(html)
parser.close()
return parser.tables
def to_number(text):
"""Convert text such as '4.75' to a number; return None when it is not numeric."""
try:
return float(text)
except ValueError:
return None
def save_csv(table, filename):
with open(filename, "w", newline="", encoding="utf-8") as f:
csv.writer(f).writerows(table["rows"])
def to_records(table):
"""Turn rows into a list of dicts keyed by the header row (empty headers are skipped)."""
header = table["rows"][0]
records = []
for row in table["rows"][1:]:
record = {}
for name, value in zip(header, row):
if name:
record[name] = value
records.append(record)
return records
def summarize(table):
"""Print the table nicely, plus the sum of every column that is fully numeric."""
header, body = table["rows"][0], table["rows"][1:]
print(f"Table '{table['caption']}': {len(body)} rows, {len(header)} columns")
widths = [max(len(r[i]) for r in table["rows"] if i < len(r)) for i in range(len(header))]
for row in table["rows"]:
print(" " + " | ".join(c.ljust(w) for c, w in zip(row, widths)))
for i, name in enumerate(header):
values = [to_number(r[i]) for r in body if i < len(r)]
if values and all(v is not None for v in values):
print(f" total {name}: {sum(values):g}")
class PageHandler(BaseHTTPRequestHandler):
def do_GET(self):
body = PAGE.encode("utf-8")
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, fmt, *args):
pass
def main():
server = ThreadingHTTPServer(("127.0.0.1", 0), PageHandler)
port = server.server_address[1]
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
try:
with urllib.request.urlopen(f"http://127.0.0.1:{port}/", timeout=5) as resp:
html = resp.read().decode("utf-8")
finally:
server.shutdown()
server.server_close()
thread.join()
print(f"Fetched {len(html)} characters from the local server")
tables = parse_tables(html)
print(f"Found {len(tables)} tables\n")
for number, table in enumerate(tables, start=1):
summarize(table)
filename = f"table{number}.csv"
save_csv(table, filename)
print(f" first record: {to_records(table)[0]}")
print(f" saved to {filename}\n")
if __name__ == "__main__":
main()
Code explanation
Event-based parsing
HTMLParser calls handle_starttag, handle_data and handle_endtag as it reads. You keep state in attributes to know where you are.
Cleaning text
' '.join(text.split()) removes extra spaces, tabs and newlines. The br tag adds a space so 'Ben<br>Smith' becomes 'Ben Smith'.
Entities
convert_charrefs=True makes the parser turn & into &, so you do not decode entities yourself.
colspan
A wide cell appears once in the HTML but covers several columns. Adding empty fillers keeps column indexes consistent.
Safe numeric totals
to_number() returns None for text. A column is only summed when every value converts, so text columns are skipped.
Expected output
Fetched 584 characters from the local server
Found 2 tables
Table 'Fruit prices': 3 rows, 3 columns
Fruit | Price | Stock
Apple | 1.20 | 40
Banana & Co | 0.50 | 120
Cherry | 4.75 | 8
total Price: 6.45
total Stock: 168
first record: {'Fruit': 'Apple', 'Price': '1.20', 'Stock': '40'}
saved to table1.csv
Table 'Team': 2 rows, 3 columns
Name | Contact |
Ana | ana@example.com | 555-0101
Ben Smith | no contact |
first record: {'Name': 'Ana', 'Contact': 'ana@example.com'}
saved to table2.csv
Common errors and solutions
Solution: Rows can have different lengths. Check i < len(row) before reading a column, as summarize() does.
Solution: Open the file with newline='' when using csv.writer.
Solution: Only collect data while self.cell is not None.
Solution: This simple parser expects flat tables. Use a stack of tables to support nesting.
Ideas to improve the project
- Read HTML from a file given on the command line
- Support rowspan
- Pick tables by id with a command-line option
- Export to JSON as well as CSV
- Add nested table support using a stack