SPB Git

Repository Public

loco.py 8.9 KB 214 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Food·Ka9# File             : foodka/connectors/loco.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 — connecteur Épiceries LOCO (epicerie-loco-en-ligne.square.site —89# épicerie écologique zéro déchet, Montréal)90# Auteur : Simon-Pierre Boucher — contact@spboucher.ai91# Square Online (SPA Vue) : aucun prix dans le HTML statique ni d'API catalogue92# publique — les grilles /shop/<slug>/<id> sont rendues côté client. Stratégie :93# Scrapfly render_js sur une sélection de catégories alimentaires (?limit=120,94# une page suffit : ~176 produits alimentaires au total), cartes95# div.product-group (titre p.w-product-title, prix « $7.30 »).96# -----------------------------------------------------------------------------97from __future__ import annotations9899import re100101from bs4 import BeautifulSoup102103from ..schema import Product104from .base import BaseConnector105106BASE = "https://epicerie-loco-en-ligne.square.site"107108# /product/<slug>/<id>?cp=true&category_id=… -> id (numérique ou uid Square)109_ID_RE = re.compile(r"/product/[^/]+/([^/?#]+)")110_PRICE_RE = re.compile(r"\$\s*(\d{1,4}(?:[.,]\d{1,2})?)")111112# catégories Square Online de LOCO : (slug/id, taxonomie source, catégorie canonique)113COLLECTIONS = [114    ("Fruit/26", "Fruits", "Fruits et légumes"),115    ("Legume/27", "Légumes", "Fruits et légumes"),116    ("produits-laitiers-et-oeufs/29", "Produits laitiers et oeufs",117     "Produits laitiers et œufs"),118    ("riz-grains-et-legumineuses/16", "Riz, graines et légumineuses",119     "Garde-manger"),120    ("Cereales-et-granola/18", "Céréales, granola et flocons d'avoine",121     "Garde-manger"),122    ("Colllations/31", "Collations", "Collations et confiseries"),123    ("Breuvage/24", "Breuvages", "Boissons"),124    ("noix/39", "Noix", "Collations et confiseries"),125    ("tartinade-et-beurre-de-noix/22", "Tartinades et beurres de noix",126     "Garde-manger"),127    ("Pret-a-manger/25", "Prêt-à-manger", "Prêt-à-manger"),128]129130131class LocoConnector(BaseConnector):132    source_id = "loco"133    request_delay = 1.0134135    page_limit: int = 120     # produits par grille (?limit=…) — 1 requête/catégorie136137    # -- extraction d'une grille de catégorie -----------------------------------138    def _parse(self, html: str, category_raw: str, category: str) -> list[Product]:139        soup = BeautifulSoup(html, "html.parser")140        products: list[Product] = []141        for card in soup.select("div.product-group"):142            link = card.select_one('a[href^="/product/"]')143            if link is None:144                continue145            m = _ID_RE.search(link.get("href", ""))146            if m is None:147                continue148            title = card.select_one("p.w-product-title")149            name = title.get_text(" ", strip=True) if title else ""150            if not name:151                img_alt = card.select_one("img[alt]")152                name = str(img_alt["alt"]).strip() if img_alt else ""153            if not name:154                continue155            # prix « $7.30 » ou plage de formats vrac « $4.55 - $6.55 »156            # (prix du plus petit format) ; un solde affiche un prix barré157            # dans un élément <s>/<del>.158            price_el = card.select_one(".product-price__wrapper") or card159            price_label = price_el.get_text(" ", strip=True)160            amounts = [float(v.replace(",", "."))161                       for v in _PRICE_RE.findall(price_label)]162            if not amounts:163                continue            # carte sans prix affiché : on l'écarte164            price = min(amounts)165            struck = price_el.select_one("s, del")166            regular = (max(amounts)167                       if struck is not None and max(amounts) > price else None)168169            low = card.get_text(" ", strip=True).lower()170            in_stock: bool | None = None171            if "épuisé" in low or "sold out" in low:172                in_stock = False173174            img = card.select_one("img[src]")175            image = str(img["src"]) if img else ""176            href = str(link["href"]).split("?", 1)[0]177178            products.append(Product(179                source=self.source_id,180                external_id=m.group(1),181                url=f"{BASE}{href}",182                name=name,183                category=category,184                category_raw=category_raw,185                price=price,186                regular_price=regular,187                price_label=price_label,188                on_sale=regular is not None,189                in_stock=in_stock,190                images=[image] if image.startswith("http") else [],191            ))192        return products193194    # -- contrat ---------------------------------------------------------------195    def fetch(self) -> list[Product]:196        products: list[Product] = []197        seen: set[str] = set()198        for slug, category_raw, category in COLLECTIONS:199            url = (f"{BASE}/shop/{slug}?page=1&limit={self.page_limit}"200                   "&sort_by=category_order&sort_order=asc")201            try:202                html = self.get_scrapfly(203                    url, render_js=True,204                    wait_for_selector="a.product-image__link",205                    must_contain="product-image__link",206                    accept=lambda h, r=category_raw, c=category: bool(self._parse(h, r, c)))207            except Exception:   # une catégorie qui casse ne bloque pas le reste208                continue209            for prod in self._parse(html, category_raw, category):210                if prod.uid not in seen:211                    seen.add(prod.uid)212                    products.append(prod)213        return products214
Files main
Menu

Theme