File size: 4,561 Bytes
5af6ad9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
#!/usr/bin/env python3
"""Capture the Salesbridges plastic-crates catalogue into raw/.

Salesbridges runs on Lightspeed eCom (formerly SEOshop — the giveaway is
cdn.webshopapp.com in the page source). Any Lightspeed storefront serves the
same page as JSON if you append `?format=json`, both for a category:

    /en/products/plastic-crates/?format=json&limit=100

and for a single product:

    /en/eurobox-60x40x32-cm-open-handle-euro-container-clo.html?format=json

The category payload has no `content` field, so the spec table — and with it the
internal dimensions, which are the reason this vendor is in the dataset — only
comes from the per-product fetch. Hence one request per product.

This is the only script here that touches the network. Run it to refresh the
snapshot; `build_listings.py` then reads the snapshot and never fetches anything,
so a rebuild always reproduces the same table.

Run: python3 scripts/capture_salesbridges.py
"""

import html
import json
import re
import time
import urllib.request
from datetime import date
from pathlib import Path

RAW = Path(__file__).resolve().parent.parent / "raw"
BASE = "https://www.salesbridges.eu/en"
CATEGORY = "products/plastic-crates"
UA = "Mozilla/5.0 (compatible; storage-container-dimensions/1.0)"
DELAY_S = 0.5

SPEC_RE = re.compile(r"([A-Za-z][A-Za-z /()xX.]*?)\s*\|\s*([^|]+)")


def get(url):
    req = urllib.request.Request(url, headers={"User-Agent": UA})
    with urllib.request.urlopen(req, timeout=45) as r:
        return json.loads(r.read().decode("utf-8"))


def spec_table(content_html):
    """Flatten the HTML spec table in `content` to {label: value}.

    The table is hand-built per product and the markup varies (extra spans, a
    stray <hr>, occasional &nbsp;), so it is cheaper to strip tags to
    cell-delimited text than to parse the table structure.
    """
    if not content_html:
        return {}
    text = re.sub(r"<t[dh][^>]*>", "|", content_html, flags=re.I)
    text = re.sub(r"<[^>]+>", " ", text)
    text = html.unescape(text).replace("\xa0", " ")
    cells = [c.strip() for c in text.split("|")]
    specs = {}
    for label, value in zip(cells, cells[1:]):
        label = re.sub(r"\s+", " ", label)
        value = re.sub(r"\s+", " ", value)
        if label and value and len(label) < 60:
            specs.setdefault(label, value)
    return specs


def main():
    cat = get(f"{BASE}/{CATEGORY}/?format=json&limit=100")["collection"]
    products = cat["products"]
    products = list(products.values()) if isinstance(products, dict) else products
    if cat["pages"] > 1:
        raise SystemExit(f"{cat['pages']} pages — raise the limit or paginate")

    out = []
    for i, p in enumerate(products, 1):
        detail = get(f"{BASE}/{p['url']}?format=json")["product"]
        specs = spec_table(detail.get("content"))
        out.append({
            "title": detail["title"],
            "variant": detail.get("variant") or "",
            "sku": detail.get("sku") or "",
            "ean": detail.get("ean") or "",
            "url": f"{BASE}/{p['url']}",
            # price_excl / price_incl: Dutch VAT is 21 % and the storefront shows
            # incl by default. listings.csv carries the ex-VAT figure to stay
            # comparable with the other vendors.
            "price_excl": detail["price"]["price_excl"],
            "price_incl": round(detail["price"]["price_incl"], 2),
            "currency": "EUR",
            # `size` is the vendor's own L/W/H in cm, independent of the spec
            # table, and is a useful cross-check on the parsed dimensions.
            "size_cm": detail.get("size"),
            "weight_g": detail.get("weight"),
            "specs": specs,
            "description": (detail.get("description") or "").strip(),
        })
        print(f"  {i}/{len(products)} {detail['title'][:60]}")
        time.sleep(DELAY_S)

    snapshot = {
        "vendor": "salesbridges",
        "collection": CATEGORY.split("/")[-1],
        "source_url": f"{BASE}/{CATEGORY}/?format=json&limit=100",
        "captured_utc": date.today().isoformat(),
        "product_count": len(out),
        "products": out,
    }
    path = RAW / f"salesbridges-plastic-crates-{snapshot['captured_utc']}.json"
    path.write_text(json.dumps(snapshot, ensure_ascii=False, indent=1), encoding="utf-8")
    with_internal = sum(1 for p in out if any("nternal" in k for k in p["specs"]))
    print(f"{len(out)} products -> {path.name} ({with_internal} publish internal dimensions)")


if __name__ == "__main__":
    main()