SPB Git

Repository Public

mayrand.py 8.2 KB 206 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Food·Ka9# File             : foodka/connectors/mayrand.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 Mayrand (mayrand.ca — grossiste alimentaire)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# HubSpot CMS : chaque page de rayon (/fr/nos-produits/<rayon>) rend TOUS les91# produits côté serveur (la pagination est purement JavaScript) — un seul GET92# par rayon suffit. Cartes : .product-card-wrapper (prix, format, image, SKU).93# -----------------------------------------------------------------------------94from __future__ import annotations9596import re9798from bs4 import BeautifulSoup99100from ..schema import Product, parse_price101from .base import BaseConnector102103BASE = "https://mayrand.ca"104105# (slug de rayon, catégorie canonique)106DEPARTMENTS = [107    ("fruits-et-legumes", "Fruits et légumes"),108    ("boucherie", "Viandes et volailles"),109    ("poissonnerie", "Poissons et fruits de mer"),110    ("charcuterie", "Charcuteries et fromages"),111    ("produits-laitiers", "Produits laitiers et œufs"),112    ("boulangerie", "Boulangerie"),113    ("surgele", "Surgelés"),114    ("epicerie", "Garde-manger"),115    ("boisson", "Boissons"),116]117118_PAREN_RE = re.compile(r"\(([^)]+)\)")     # « caisse (11.34kg) » -> « 11.34kg »119_SKU_RE = re.compile(r"-(\d+)/?$")         # slug produit : ...-<sku>120121122class MayrandConnector(BaseConnector):123    source_id = "mayrand"124125    max_departments: int | None = None     # borne pour les tests126    max_per_department: int = 50           # ~450 produits/synchro au total127128    def _parse_cards(self, html: str, category: str, slug: str) -> list[Product]:129        soup = BeautifulSoup(html, "html.parser")130        products: list[Product] = []131        for card in soup.select("div.product-card-wrapper"):132            link = card.select_one("a.product_link[href]")133            if link is None:134                continue135            name = link.get_text(" ", strip=True)136            href = link["href"]137            sku_el = card.select_one(".product_id")138            sku = sku_el.get_text(strip=True) if sku_el else ""139            if not sku:140                m = _SKU_RE.search(href)141                sku = m.group(1) if m else ""142            if not name or not sku:143                continue144145            # premier bloc de prix (« unité » avant « caisse » quand les deux existent)146            price_el = card.select_one(".unit_price")147            regular = None148            price_label = ""149            if price_el is not None:150                deleted = price_el.select_one("del.price-discount")151                if deleted is not None:               # en solde : <span> prix, <del> régulier152                    regular = parse_price(deleted.get_text(" ", strip=True))153                    span = price_el.select_one("span")154                    price_label = span.get_text(" ", strip=True) if span else ""155                else:156                    price_label = price_el.get_text(" ", strip=True)157158            qty_el = card.select_one(".unit_quantity")159            qty_text = qty_el.get_text(" ", strip=True) if qty_el else ""160            m = _PAREN_RE.search(qty_text)161            size_label = m.group(1) if m else ""162163            unit_el = card.select_one(".unit-price-ref")164            img = card.select_one("img.product_image[src]")165            image = str(img["src"]) if img else ""166            brand = (card.get("data-brand") or "").strip()167            if brand.lower() == "null":168                brand = ""169170            products.append(Product(171                source=self.source_id,172                external_id=sku,173                url=f"{BASE}/fr/nos-produits/{href.lstrip('/')}",174                name=name,175                brand=brand,176                category=category,177                category_raw=slug,178                size_label=size_label,179                price_label=price_label,180                regular_price=regular,181                on_sale=card.get("data-sale") == "OnSale",182                unit_price_label=unit_el.get_text(" ", strip=True) if unit_el else "",183                details={"format": qty_text} if qty_text else {},184                images=[image] if image.startswith("http") else [],185            ))186        return products187188    def fetch(self) -> list[Product]:189        products: list[Product] = []190        seen: set[str] = set()191        departments = DEPARTMENTS[: self.max_departments]192        for slug, category in departments:193            url = f"{BASE}/fr/nos-produits/{slug}"194            try:195                html = self.get(url).text196            except Exception:   # un rayon qui casse ne bloque pas le reste197                continue198            kept = 0199            for prod in self._parse_cards(html, category, slug):200                if prod.uid in seen or kept >= self.max_per_department:201                    continue202                seen.add(prod.uid)203                products.append(prod)204                kept += 1205        return products206
Files main
Menu

Theme