|
| 1 | +"""Validate scraped records and store them, de-duplicated, in SQLite. |
| 2 | +
|
| 3 | +Companion code for: |
| 4 | +- https://python-web-scraping.com/scaling-python-web-scrapers/storing-and-exporting-scraped-data/ |
| 5 | +""" |
| 6 | + |
| 7 | +from __future__ import annotations |
| 8 | + |
| 9 | +import sqlite3 |
| 10 | + |
| 11 | +from pydantic import BaseModel, ValidationError, field_validator |
| 12 | + |
| 13 | + |
| 14 | +class Product(BaseModel): |
| 15 | + """A validated product record. ``price`` is coerced from strings like '£42.00'.""" |
| 16 | + |
| 17 | + title: str |
| 18 | + price: float |
| 19 | + in_stock: bool = True |
| 20 | + |
| 21 | + @field_validator("price", mode="before") |
| 22 | + @classmethod |
| 23 | + def _clean_price(cls, value: object) -> float: |
| 24 | + return float(str(value).replace("£", "").replace("$", "").strip()) |
| 25 | + |
| 26 | + |
| 27 | +def validate(rows: list[dict]) -> list[Product]: |
| 28 | + """Validate raw dict rows into ``Product`` models, skipping malformed ones.""" |
| 29 | + products: list[Product] = [] |
| 30 | + for row in rows: |
| 31 | + try: |
| 32 | + products.append(Product(**row)) |
| 33 | + except ValidationError: |
| 34 | + continue |
| 35 | + return products |
| 36 | + |
| 37 | + |
| 38 | +def store_sqlite(products: list[Product], conn: sqlite3.Connection) -> int: |
| 39 | + """Create the table if needed and insert, de-duplicating by title. |
| 40 | +
|
| 41 | + Returns the number of rows actually inserted. |
| 42 | + """ |
| 43 | + conn.execute( |
| 44 | + "CREATE TABLE IF NOT EXISTS products (" |
| 45 | + "title TEXT UNIQUE, price REAL, in_stock INTEGER)" |
| 46 | + ) |
| 47 | + before = conn.total_changes |
| 48 | + conn.executemany( |
| 49 | + "INSERT OR IGNORE INTO products (title, price, in_stock) VALUES (?, ?, ?)", |
| 50 | + [(p.title, p.price, int(p.in_stock)) for p in products], |
| 51 | + ) |
| 52 | + conn.commit() |
| 53 | + return conn.total_changes - before |
| 54 | + |
| 55 | + |
| 56 | +if __name__ == "__main__": |
| 57 | + connection = sqlite3.connect(":memory:") |
| 58 | + records = validate([{"title": "Clean Code", "price": "£42.00"}, {"title": "no price"}]) |
| 59 | + print("stored:", store_sqlite(records, connection)) |
0 commit comments