Lesson 7 of 9 · 24m
Extraction, Schemas, and Normalization
Turn unstable presentation into typed records with explicit selectors, validation, normalization, and quarantine paths for malformed input.
HTML is a presentation artifact. Your dataset wants entities. The distance between those two things is where scraping projects rot: prices with currency symbols embedded, dates in three locales, nested cards reused for different products, missing values rendered as dashes, and selectors that silently match the wrong node. Extraction deserves the same rigor as any untrusted-input boundary.
Extract close to meaning
Prefer stable selectors over cosmetic structure:
from selectolax.parser import HTMLParser
tree = HTMLParser(html)
for card in tree.css("article.product_pod"):
yield {
"title": card.css_first("h3 a").attributes.get("title"),
"price_text": card.css_first(".price_color").text(strip=True),
"detail_path": card.css_first("h3 a").attributes.get("href"),
}Generated classes, sibling positions, and long XPath ladders are brittle. data-* attributes, semantic elements, ARIA labels, and item IDs are better anchors when they exist.
Parse types at the boundary
Do not let strings shaped like numbers wander downstream:
from decimal import Decimal
from pydantic import BaseModel, Field, field_validator
class ProductObservation(BaseModel):
title: str = Field(min_length=1)
price: Decimal
currency: str
@field_validator("price", mode="before")
@classmethod
def parse_price(cls, value):
return Decimal(str(value).replace("£", "").replace(",", "").strip())Validation failures should quarantine the raw page and extracted fragment. Dropping them silently teaches your metrics to lie.
Normalize units, locale, and identity
Normalization is not cosmetic cleanup. It defines comparability:
price Decimal plus ISO 4217 currency
time UTC timestamp plus source-local observation time if needed
text Unicode NFC, whitespace collapsed deliberately
URLs absolute, canonicalized, source preserved
identifiers source-native ID preferred over hash of presentation
availability controlled enum: in_stock / out_of_stock / unknownDo not over-normalize. If exact text matters legally or analytically, preserve the raw value beside the normalized one.
Schema versioning is operational armor
Websites change without notice. Carry schema_version, source_url, observed_at, and extractor_version on every record. When drift happens, you can reprocess raw captures with the corrected extractor instead of guessing which database rows are poisoned.
Assertions beat hope
Write fixture tests from real captured pages: expected row count, required fields, and typed values. Update fixtures intentionally. A fixture that changes on every run is not a test; it is a screenshot of chaos.
Field notes
- Never use a successful selector count as proof the right nodes were selected.
- Unicode normalization can destroy meaningful distinctions in names; choose intentionally.
- Money is not a float. Use decimal arithmetic and keep currency with the amount.
- Missing and zero are different facts. Do not let a parser collapse them.
- Quarantined records need ownership and expiry, or the quarantine becomes a second broken dataset.
Was this lesson helpful?