5. Web Scraping & Workflow Automation

Practice Lab 2: HTML Catalog Extractor & Automated KPI Report

Combine scraping, data cleaning, statistics, and automated reporting in one lab: extract product cards from HTML, compute category medians & totals, and export a clean CSV report.

5 min readUpdated 2026-11-30
In This Lesson
  • Extract structured product records from raw HTML markup
  • Clean extracted price strings and compute per-category totals and medians
  • Write a sorted CSV summary report via pathlib and verify with assert checks

Time to connect Modules 3, 4, and 5 in one realistic automation drill! Imagine your Merchandising team tracks competitor catalog pricing every week from a public HTML product directory. Instead of copying prices by hand into Excel, you will build an end-to-end mini-pipeline that:

  1. Extracts structured product cards from HTML markup (CatalogParser),
  2. Cleans "$1,299.00" currency strings safely while ignoring malformed entries,
  3. Computes skew-resistant category KPIs (count, total, median), and
  4. Exports an atomic, sorted .csv KPI report using pathlib and csv.DictWriter.

1. Pipeline Data-Flow Breakdown

StageInputOutputDefensive Guard
1. ExtractRaw HTML <li> catalogTuples (category, name, raw_price)Reset _cat = None in handle_endtag
2. Clean"$89.00" or "TBD"float price per categoryWrap float(...) in try/except ValueError
3. Summarizedict[str, list[float]]{category: {"count", "total", "median"}}Use statistics.median (resists $310+ spikes!)
4. ExportSummary dictionarySorted .csv via tmp.replace()mkdir(parents=True, exist_ok=True) + newline=""
Watch Out for Multi-Part Text Inside HTML Tags

HTMLParser.handle_data(data) can be invoked more than once per element if an HTML tag contains entities (like &amp;) or whitespace breaks. Always verify self._cat is active and reset state cleanly inside handle_endtag("li")!

2. Your Mission

Implement analyze_catalog(html_text: str) -> dict[str, dict] and export_report(report: dict[str, dict], out_path: Path) -> None in the playground below:

  1. Parse every <li data-category="...">Name — $Price</li> item using CatalogParser.
  2. Clean the price string (strip commas/spaces, parse float, skip unparseable or <= 0 prices).
  3. Return {category: {"count": int, "total": float, "median": float}} with total and median rounded to 2 decimals.
  4. (Bonus step) Write report sorted by descending total to /tmp/catalog_kpi.csv with headers category,count,total,median.
  5. Uncomment the assert block and run to verify!
Python 3Lab 2: Scrape HTML Catalog & Build KPI Summary
Output

Click “Run Code” to execute this snippet right in your browser.

Line-by-Line Walkthrough of Subtle Details

  1. Why median instead of mean for "Hardware"? Notice "Hardware" has two $35–$89 accessories and one $310 4K monitor. The mean jumps to $144.67 (higher than 2 of the 3 items!), whereas statistics.median([89.0, 35.0, 310.0]) is $89.00—an honest typical item price.
  2. Why newline="" when opening CSV files in Python? On Windows (and portable scripts), csv.DictWriter writes \r\n endings itself; omitting newline="" causes double blank lines between rows.
  3. Why check if prices: before calling statistics.median(prices)? Calling statistics.median([]) on an empty list raises StatisticsError. Skipping categories with zero valid prices keeps your aggregator crash-proof.

Lab Checklist & Quick Checkpoints

Lab 2 Completion Checklist

0/4 done
Check Your Understanding

In Hardware ($89, $35, $310), why does statistics.median give $89.0 while mean gives $144.67?

Check Your Understanding

When exporting report with csv.DictWriter, why should you pass newline='' inside open(..., 'w', encoding='utf-8', newline='')?