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.
- 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:
- Extracts structured product cards from HTML markup (
CatalogParser), - Cleans
"$1,299.00"currency strings safely while ignoring malformed entries, - Computes skew-resistant category KPIs (
count,total,median), and - Exports an atomic, sorted
.csvKPI report usingpathlibandcsv.DictWriter.
1. Pipeline Data-Flow Breakdown
| Stage | Input | Output | Defensive Guard |
|---|---|---|---|
| 1. Extract | Raw HTML <li> catalog | Tuples (category, name, raw_price) | Reset _cat = None in handle_endtag |
| 2. Clean | "$89.00" or "TBD" | float price per category | Wrap float(...) in try/except ValueError |
| 3. Summarize | dict[str, list[float]] | {category: {"count", "total", "median"}} | Use statistics.median (resists $310+ spikes!) |
| 4. Export | Summary dictionary | Sorted .csv via tmp.replace() | mkdir(parents=True, exist_ok=True) + newline="" |
HTMLParser.handle_data(data) can be invoked more than once per element if an HTML tag contains entities (like &) 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:
- Parse every
<li data-category="...">Name — $Price</li>item usingCatalogParser. - Clean the price string (strip commas/spaces, parse
float, skip unparseable or<= 0prices). - Return
{category: {"count": int, "total": float, "median": float}}withtotalandmedianrounded to 2 decimals. - (Bonus step) Write
reportsorted by descendingtotalto/tmp/catalog_kpi.csvwith headerscategory,count,total,median. - Uncomment the
assertblock and run to verify!
Click “Run Code” to execute this snippet right in your browser.
Line-by-Line Walkthrough of Subtle Details
- Why median instead of mean for
"Hardware"? Notice"Hardware"has two$35–$89accessories and one$3104K monitor. The mean jumps to$144.67(higher than 2 of the 3 items!), whereasstatistics.median([89.0, 35.0, 310.0])is$89.00—an honest typical item price. - Why
newline=""when opening CSV files in Python? On Windows (and portable scripts),csv.DictWriterwrites\r\nendings itself; omittingnewline=""causes double blank lines between rows. - Why check
if prices:before callingstatistics.median(prices)? Callingstatistics.median([])on an empty list raisesStatisticsError. Skipping categories with zero valid prices keeps your aggregator crash-proof.
Lab Checklist & Quick Checkpoints
Lab 2 Completion Checklist
0/4 doneIn Hardware ($89, $35, $310), why does statistics.median give $89.0 while mean gives $144.67?
When exporting report with csv.DictWriter, why should you pass newline='' inside open(..., 'w', encoding='utf-8', newline='')?