storage-container-dimensions / scripts /capture_salesbridges.py
danielrosehill's picture
Add Salesbridges, the vendor internal-dimension spread, and naming guidance
5af6ad9
Raw
History Blame Contribute Delete
4.56 kB
#!/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()