SPB Git

Repository Public

avril.py 8.1 KB 204 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Food·Ka9# File             : foodka/connectors/avril.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 Avril Supermarché Santé (avril.ca)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# Magento 2 (thème Hyvä/Alpine) : les sous-catégories d'épicerie91# (/fr/epicerie/<sous-cat>.html?p=N, 24 cartes/page) sont rendues côté92# serveur. Cloudflare en façade mais le GET direct passe ; repli Scrapfly93# (ASP) si 403. NB : dans le balisage Avril, .price = prix courant et94# .special-price = prix régulier barré (nommage inversé).95# -----------------------------------------------------------------------------96from __future__ import annotations9798import re99100from bs4 import BeautifulSoup101102from ..schema import Product, parse_price103from .base import BaseConnector104105BASE = "https://avril.ca"106107# (slug de sous-catégorie d'épicerie, catégorie canonique)108CATEGORIES = [109    ("fruits-legumes-biologiques", "Fruits et légumes"),110    ("viandes-substituts", "Viandes et volailles"),111    ("poissons-fruits-de-mer", "Poissons et fruits de mer"),112    ("produits-laitiers-oeufs", "Produits laitiers et œufs"),113    ("boulangerie", "Boulangerie"),114    ("garde-manger", "Garde-manger"),115    ("boissons", "Boissons"),116    ("pret-a-manger", "Prêt-à-manger"),117]118119_IMG_RE = re.compile(r"initImage\('([^']+)'\)")120121122class AvrilConnector(BaseConnector):123    source_id = "avril"124125    max_categories: int | None = None    # borne pour les tests126    pages_per_category: int = 2          # 24 cartes/page -> ~384 produits max127128    def _get_html(self, url: str) -> str:129        """GET direct d'abord ; Scrapfly (ASP) si Cloudflare bloque (403)."""130        try:131            return self.get(url).text132        except Exception:133            return self.get_scrapfly(url)134135    def _parse_cards(self, html: str, category: str, slug: str) -> list[Product]:136        soup = BeautifulSoup(html, "html.parser")137        products: list[Product] = []138        for card in soup.select("form.product-item"):139            link = card.select_one("a.product-item-link[href]")140            pid_el = card.select_one('input[name="product"][value]')141            if link is None or pid_el is None:142                continue143            name = link.get_text(" ", strip=True)144            pid = str(pid_el["value"])145            if not name or not pid:146                continue147148            weight_el = card.select_one(".product-item-weight")149            size_label = ""150            if weight_el is not None:151                size_label = weight_el.get_text(" ", strip=True).lstrip("| ").strip()152153            brand_el = card.select_one(".product-info-brand")154            price_el = card.select_one(".price-container .price")155            # nommage Avril inversé : .special-price = prix régulier barré156            regular_el = card.select_one(".price-container .special-price")157158            image = ""159            img = card.select_one("img.product-image-photo")160            if img is not None:161                m = _IMG_RE.search(str(img.get("x-data") or ""))162                if m:163                    image = m.group(1)164165            products.append(Product(166                source=self.source_id,167                external_id=pid,168                url=str(link["href"]),169                name=name,170                brand=brand_el.get_text(" ", strip=True) if brand_el else "",171                category=category,172                category_raw=f"epicerie/{slug}",173                size_label=size_label,174                price_label=price_el.get_text(" ", strip=True) if price_el else "",175                regular_price=(parse_price(regular_el.get_text(" ", strip=True))176                               if regular_el else None),177                on_sale=regular_el is not None,178                images=[image] if image.startswith("http") else [],179            ))180        return products181182    def fetch(self) -> list[Product]:183        products: list[Product] = []184        seen: set[str] = set()185        categories = CATEGORIES[: self.max_categories]186        for slug, category in categories:187            for page in range(1, self.pages_per_category + 1):188                url = f"{BASE}/fr/epicerie/{slug}.html"189                if page > 1:190                    url += f"?p={page}"191                try:192                    html = self._get_html(url)193                except Exception:   # une page qui casse ne bloque pas le reste194                    break195                new = 0196                for prod in self._parse_cards(html, category, slug):197                    if prod.uid not in seen:198                        seen.add(prod.uid)199                        products.append(prod)200                        new += 1201                if new == 0:        # page vide ou répétée : catégorie épuisée202                    break203        return products204
Files main
Menu

Theme