Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Food·Ka9# File : foodka/connectors/_loblaw.py10# Module : foodka11# Repository : https://git.spboucher.ai/food-ka12# Created : 2026-08-1213# Last Modified : 2026-08-1214#15# =============================================================================16# AUTHOR & PROFESSIONAL AFFILIATION17# =============================================================================18#19# Author : Simon-Pierre Boucher20# Position : Professor of Finance21# Institution : Université du Québec en Outaouais (UQO)22# Department : Département des sciences administratives23# Organization : SP Boucher24#25# Website : https://spboucher.ai26# Git : https://git.spboucher.ai27#28# =============================================================================29# OFFICIAL CONTACT DIRECTORY30# =============================================================================31#32# General : info@spboucher.ai33# Professional : contact@spboucher.ai34# Direct : simon@spboucher.ai35# Research : research@spboucher.ai36# Development : dev@spboucher.ai37# Support : support@spboucher.ai38# Security/Admin : admin@spboucher.ai39# Notifications : notifications@spboucher.ai40#41# Preferred Contact: contact@spboucher.ai42#43# =============================================================================44# COPYRIGHT & INTELLECTUAL PROPERTY45# =============================================================================46#47# Copyright (c) 202648# Simon-Pierre Boucher49#50# All rights reserved where applicable.51#52# This file is governed by the applicable project license,53# copyright notices, institutional agreements and relevant law.54#55# Unless expressly authorized by the applicable license or56# rights holder, copying, redistribution, sublicensing,57# publication and commercial exploitation are not permitted.58#59# Existing third-party rights and notices remain unaffected.60#61# =============================================================================62# CONFIDENTIALITY & SECURITY63# =============================================================================64#65# Classification : Public66# Distribution : Public repository; use is governed by the project license67# Security Contact : admin@spboucher.ai68#69# Access to this source does not independently grant permission70# to redistribute or disclose confidential materials.71#72# Do not embed credentials, private keys, access tokens,73# certificates or confidential personal information.74#75# =============================================================================76# LICENSE & MAINTENANCE77# =============================================================================78#79# License : None specified (no license file in this repository)80# Maintainer : Simon-Pierre Boucher81# Technical Contact: dev@spboucher.ai82#83# =============================================================================84# END OF SP BOUCHER SOURCE HEADER85# =============================================================================8687# -----------------------------------------------------------------------------88# Food-Ka — Agrégateur de produits d'épicerie (province de Québec)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# connectors/_loblaw.py : socle commun des bannières Loblaw (Maxi, Provigo)91# Les sites Loblaw (Next.js) embarquent la grille produits complète dans92# <script id="__NEXT_DATA__"> ; on la lit derrière l'anti-bot via Scrapfly.93# -----------------------------------------------------------------------------94from __future__ import annotations9596import json97import re9899from ..schema import Product, parse_price100from .base import BaseConnector101102_NEXT_RE = re.compile(103 r'<script id="__NEXT_DATA__" type="application/json">(.*?)</script>', re.S)104105# sous-catégories standard du réseau Loblaw : (slug, code, catégorie canonique)106CATEGORIES = [107 ("fruits-et-legumes", 28000, "Fruits et légumes"),108 ("viandes", 27998, "Viandes et volailles"),109 ("poissons-et-fruits-de-mer", 28004, "Poissons et fruits de mer"),110 ("charcuteries-et-fromages", 28131, "Charcuteries et fromages"),111 ("produits-laitiers-et-oeufs", 28008, "Produits laitiers et œufs"),112 ("boulangerie", 28020, "Boulangerie"),113 ("surgeles", 28195, "Surgelés"),114 ("garde-manger", 28016, "Garde-manger"),115 ("boissons", 28051, "Boissons"),116]117118119class LoblawConnector(BaseConnector):120 """Base des bannières Loblaw — sous-classes : définir source_id et domain."""121122 domain: str = "" # ex. "www.maxi.ca"123 pages_per_category: int = 2 # 48 produits/page ; ~860 produits/sync124125 def _next_data(self, url: str) -> dict | None:126 html = self.get_scrapfly(url, must_contain="__NEXT_DATA__")127 m = _NEXT_RE.search(html)128 return json.loads(m.group(1)) if m else None129130 def _tiles(self, data: dict) -> tuple[list[dict], bool]:131 """(tuiles produit, hasMore) — collecte récursive : selon la page132 (racine ou sous-catégorie), Loblaw embarque une ou plusieurs grilles133 `productTiles`, avec ou sans bloc `pagination`."""134 tiles: list[dict] = []135 has_more = False136137 def walk(o):138 nonlocal has_more139 if isinstance(o, dict):140 if "productTiles" in o:141 tiles.extend(o.get("productTiles") or [])142 if (o.get("pagination") or {}).get("hasMore"):143 has_more = True144 return145 for v in o.values():146 walk(v)147 elif isinstance(o, list):148 for v in o:149 walk(v)150151 try:152 walk(data["props"]["pageProps"]["initialData"]["layout"]["sections"])153 except (KeyError, TypeError):154 pass155 return tiles, has_more156157 def _tile_to_product(self, tile: dict, category: str,158 category_raw: str) -> Product | None:159 pid = tile.get("productId")160 if not pid:161 return None162 pricing = tile.get("pricing") or {}163 price = parse_price(pricing.get("price"))164 was = parse_price(pricing.get("wasPrice"))165 images = [img.get("largeUrl") or img.get("imageUrl")166 for img in tile.get("productImage") or [] if isinstance(img, dict)]167 link = tile.get("link") or ""168 badges = []169 deal = tile.get("deal") or {}170 if isinstance(deal, dict) and deal.get("name"):171 badges.append(str(deal["name"]))172 return Product(173 source=self.source_id,174 external_id=str(pid),175 url=f"https://{self.domain}{link}" if link.startswith("/") else link,176 name=tile.get("title") or "",177 brand=tile.get("brand") or "",178 category=category,179 category_raw=category_raw,180 size_label=tile.get("packageSizing") or "",181 price=price,182 regular_price=was,183 price_label=pricing.get("displayPrice") or "",184 on_sale=bool(was and price and was > price),185 in_stock=None,186 keywords=badges,187 details={"article": tile.get("articleNumber"),188 "uom": tile.get("uom")},189 images=[i for i in images if i],190 )191192 def fetch(self) -> list[Product]:193 products: list[Product] = []194 seen: set[str] = set()195 for slug, code, category in CATEGORIES:196 for page in range(1, self.pages_per_category + 1):197 url = f"https://{self.domain}/fr/{slug}/c/{code}?page={page}"198 try:199 data = self._next_data(url)200 except Exception: # une catégorie qui casse ne bloque pas le reste201 break202 if not data:203 break204 tiles, has_more = self._tiles(data)205 new = 0206 for tile in tiles:207 try:208 prod = self._tile_to_product(tile, category,209 slug.replace("-", " "))210 except Exception:211 continue212 if prod and prod.uid not in seen:213 seen.add(prod.uid)214 products.append(prod)215 new += 1216 # sans bloc pagination : on s'arrête dès qu'une page ne217 # rapporte plus de nouveaux produits218 if not has_more and new == 0:219 break220 return products221