SPB Git

Repository Public

adonis.py 8.5 KB 207 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Food·Ka9# File             : foodka/connectors/adonis.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 Marché Adonis (livraison.groupeadonis.ca)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# Boutique Instacart en marque blanche (SPA React) : rendu JavaScript via91# Scrapfly + attente des cartes produit a[data-item-card-button]. Les prix92# s'affichent sans session (adresse de livraison par défaut d'Instacart) —93# prix courant et prix d'origine exposés en texte lecteur d'écran94# (« Current price: … » / « Original Price: … »).95# Collections : /store/adonis/collections/{slug} (~20 produits rendus/page).96# -----------------------------------------------------------------------------97from __future__ import annotations9899import re100101from bs4 import BeautifulSoup102103from ..schema import Product, parse_price104from .base import BaseConnector105106_ID_RE = re.compile(r"/products/(\d+)")107_CURRENT_RE = re.compile(r"Current price:\s*(.+)", re.I)108_ORIGINAL_RE = re.compile(r"Original Price:\s*(.+)", re.I)109110# collections Instacart d'Adonis : (slug, catégorie canonique)111COLLECTIONS = [112    ("n-produce-56955", "Fruits et légumes"),113    ("n-meat-seafood-98116", "Viandes et volailles"),114    ("n-dairy-eggs-49119", "Produits laitiers et œufs"),115    ("n-deli-35601", "Charcuteries et fromages"),116    ("n-bakery-91773", "Boulangerie"),117    ("n-frozen-44158", "Surgelés"),118    ("n-dry-goods-pasta-75048", "Garde-manger"),119    ("n-canned-goods-soups-12716", "Garde-manger"),120    ("n-beverages-8671", "Boissons"),121    ("n-snacks-candy-4336", "Collations et confiseries"),122    ("n-prepared-foods-84844", "Prêt-à-manger"),123]124125126class AdonisConnector(BaseConnector):127    source_id = "adonis"128    request_delay = 1.0129130    # -- extraction d'une collection --------------------------------------------131    def _parse(self, html: str, category: str, slug: str) -> list[Product]:132        soup = BeautifulSoup(html, "html.parser")133        products: list[Product] = []134        for card in soup.select("a[data-item-card-button][href]"):135            href = card["href"]136            m = _ID_RE.search(href)137            title = card.select_one("h3")138            if not m or title is None:139                continue140            name = title.get_text(" ", strip=True)141            if not name:142                continue143            # prix : textes lecteur d'écran, robustes face aux classes minifiées144            text = card.get_text("\n", strip=True)145            cur_m = _CURRENT_RE.search(text)146            orig_m = _ORIGINAL_RE.search(text)147            price_label = cur_m.group(1).strip() if cur_m else ""148            price = parse_price(price_label)149            regular = parse_price(orig_m.group(1).strip()) if orig_m else None150            # format / prix unitaire : bloc qui suit le titre151            size_label, unit_label = "", ""152            after = title.find_next_sibling("div")153            if after is not None:154                after_text = after.get_text(" ", strip=True)155                if "$" in after_text:156                    unit_label = after_text157                else:158                    size_label = after_text159            # produits vendus au poids : le prix affiché est par kilogramme160            if not size_label and "per kilogram" in price_label.lower():161                size_label = "1 kg"162            in_stock: bool | None = None163            low = text.lower()164            if "out of stock" in low:165                in_stock = False166            elif "in stock" in low:167                in_stock = True168            img = card.select_one('img[data-testid="item-card-image"][src]')169            products.append(Product(170                source=self.source_id,171                external_id=m.group(1),172                url=(f"https://livraison.groupeadonis.ca{href}"173                     if href.startswith("/") else href),174                name=name,175                category=category,176                category_raw=slug,177                size_label=size_label,178                price=price,179                regular_price=regular,180                price_label=price_label,181                on_sale=regular is not None,182                unit_price_label=unit_label,183                in_stock=in_stock,184                images=[img["src"]] if img is not None else [],185            ))186        return products187188    # -- contrat ---------------------------------------------------------------189    def fetch(self) -> list[Product]:190        products: list[Product] = []191        seen: set[str] = set()192        for slug, category in COLLECTIONS:193            url = f"https://livraison.groupeadonis.ca/store/adonis/collections/{slug}"194            try:195                html = self.get_scrapfly(196                    url, render_js=True,197                    wait_for_selector="a[data-item-card-button]",198                    must_contain="data-item-card-button",199                    accept=lambda h, c=category, s=slug: bool(self._parse(h, c, s)))200            except Exception:   # une collection qui casse ne bloque pas le reste201                continue202            for prod in self._parse(html, category, slug):203                if prod.uid not in seen:204                    seen.add(prod.uid)205                    products.append(prod)206        return products207
Files main
Menu

Theme