SPB Git

Repository Public

maturin.py 7.6 KB 195 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Food·Ka9# File             : foodka/connectors/maturin.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 Maturin (maturin.ca — produits québécois en ligne)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# Site maison rendu côté serveur : /categorie/<cat>?page=N (24 cartes/page,91# défilement infini côté client = simple paramètre page). Cartes92# .masonry-product : titre, producteur (marque), prix « À partir de X$ / fmt »,93# image /image/crop/....94# -----------------------------------------------------------------------------95from __future__ import annotations9697import re9899from bs4 import BeautifulSoup100101from ..schema import Product, parse_price102from .base import BaseConnector103104BASE = "https://maturin.ca"105106# (slug de catégorie, catégorie canonique)107CATEGORIES = [108    ("fruits-et-legumes", "Fruits et légumes"),109    ("boucherie", "Viandes et volailles"),110    ("poissonnerie", "Poissons et fruits de mer"),111    ("produits-laitiers", "Produits laitiers et œufs"),112    ("boulangerie-et-desserts", "Boulangerie"),113    ("garde-manger", "Garde-manger"),114    ("breuvages", "Boissons"),115    ("mets-cuisines", "Prêt-à-manger"),116]117118# « À partir de 7.60$ / 350g » -> (prix, format)119_PRICE_FMT_RE = re.compile(r"(\d+(?:[.,]\d{1,2})?\s*\$)(?:\s*/\s*(\S+))?")120121122class MaturinConnector(BaseConnector):123    source_id = "maturin"124125    max_categories: int | None = None    # borne pour les tests126    pages_per_category: int = 2          # 24 cartes/page -> ~384 produits max127128    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.masonry-product[data-product]"):132            pid = str(card.get("data-product") or "")133            title = card.select_one(".product-title a[href]")134            if not pid or title is None:135                continue136            name = title.get_text(" ", strip=True)137            if not name:138                continue139            brand_el = card.select_one(".product-subtitle a")140141            price_label, size_label = "", ""142            price_el = card.select_one(".product-price span")143            if price_el is not None:144                text = price_el.get_text(" ", strip=True)145                m = _PRICE_FMT_RE.search(text)146                if m:147                    price_label = m.group(1)148                    size_label = m.group(2) or ""149150            img = card.select_one("img.product-image")151            src = str((img.get("data-src") or img.get("src") or "")) if img else ""152            if src.startswith("/") and "none.png" not in src:153                image = f"{BASE}{src}"154            else:155                image = src if src.startswith("http") else ""156157            href = str(title["href"])158            products.append(Product(159                source=self.source_id,160                external_id=pid,161                url=f"{BASE}{href}" if href.startswith("/") else href,162                name=name,163                brand=brand_el.get_text(" ", strip=True) if brand_el else "",164                category=category,165                category_raw=slug,166                size_label=size_label,167                price=parse_price(price_label),168                price_label=price_label,169                images=[image] if image else [],170            ))171        return products172173    def fetch(self) -> list[Product]:174        products: list[Product] = []175        seen: set[str] = set()176        categories = CATEGORIES[: self.max_categories]177        for slug, category in categories:178            for page in range(1, self.pages_per_category + 1):179                url = f"{BASE}/categorie/{slug}"180                if page > 1:181                    url += f"?url=categorie/{slug}&page={page}"182                try:183                    html = self.get(url).text184                except Exception:   # une page qui casse ne bloque pas le reste185                    break186                new = 0187                for prod in self._parse_cards(html, category, slug):188                    if prod.uid not in seen:189                        seen.add(prod.uid)190                        products.append(prod)191                        new += 1192                if new == 0:        # page vide ou répétée : catégorie épuisée193                    break194        return products195
Files main
Menu

Theme