SPB Git

Repository Public

costco.py 8.2 KB 199 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Food·Ka9# File             : foodka/connectors/costco.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 Costco Canada (costco.ca, épicerie livrée)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# Nouveau catalogue Next.js (App Router) derrière Akamai : les tuiles produit91# sont montées côté client — rendu JavaScript via Scrapfly + attente du92# sélecteur [data-testid^="ProductTile"]. Chaque page feuille (ex. crackers)93# affiche une grille de tuiles avec prix ; les pages « rayon » (ex. snacks)94# ne contiennent que des vignettes de sous-catégories, on cible donc les95# feuilles directement. Numéro d'article Costco = id dans l'URL produit.96# ⚠️ Le frais (produce, dairy, meat…) est « Warehouse Only » : aucun prix en97# ligne (« Warehouse pricing may vary ») — on ne couvre que l'épicerie livrée98# (Costco Grocery, non périssable) et on ignore les tuiles sans prix.99# -----------------------------------------------------------------------------100from __future__ import annotations101102import re103104from bs4 import BeautifulSoup105106from ..schema import Product, parse_price107from .base import BaseConnector108109# format dans le nom : "567 g", "2 × 425 g", "40 x 28 g", "1.36 kg"…110_SIZE_IN_NAME = re.compile(111    r"((?:\d+\s*[x×]\s*)?\d+(?:[.,]\d+)?\s*(?:kg|g|ml|l|lb|oz|un))\b",112    re.IGNORECASE)113114# pages feuilles (grille produits) de l'épicerie livrée : (slug, catégorie)115CATEGORIES = [116    ("canned-food", "Garde-manger"),117    ("cereal", "Garde-manger"),118    ("pasta", "Garde-manger"),119    ("oils-vinegars", "Garde-manger"),120    ("soup", "Garde-manger"),121    ("spreads-butters", "Garde-manger"),122    ("baking-packaged-food", "Garde-manger"),123    ("soda-soft-drinks", "Boissons"),124    ("juice", "Boissons"),125    ("ground-coffee", "Boissons"),126    ("tea", "Boissons"),127    ("crackers", "Collations et confiseries"),128    ("chocolates", "Collations et confiseries"),129    ("candy", "Collations et confiseries"),130    ("fruit-nuts", "Collations et confiseries"),131    ("organic", "Bio et santé"),132    ("laundry-detergent", "Maison et entretien"),133]134135136class CostcoConnector(BaseConnector):137    source_id = "costco"138    request_delay = 1.0139140    # -- extraction d'une grille -----------------------------------------------141    def _parse(self, html: str, category: str, slug: str) -> list[Product]:142        soup = BeautifulSoup(html, "html.parser")143        products: list[Product] = []144        for tile in soup.select('div[data-testid^="ProductTile_"]'):145            pid = tile.get("data-testid", "").split("_", 1)[-1]146            link = tile.select_one('a[data-testid="Link"][href]')147            if not pid or link is None:148                continue149            name = link.get_text(" ", strip=True)150            if not name:151                continue152            price_el = tile.select_one('[data-testid^="Text_Price"]')153            price = parse_price(price_el.get_text(" ", strip=True)) if price_el else None154            if price is None:   # tuile « Warehouse Only » : pas de prix en ligne155                continue156            img = tile.select_one('[data-testid^="ProductImage"] img[src]')157            size_m = _SIZE_IN_NAME.search(name)158            text = tile.get_text(" ", strip=True)159            in_stock: bool | None = None160            if "Out of Stock" in text:161                in_stock = False162            elif "In Stock" in text or "Add to Cart" in text:163                in_stock = True164            href = link["href"]165            products.append(Product(166                source=self.source_id,167                external_id=str(pid),168                url=href if href.startswith("http") else f"https://www.costco.ca{href}",169                name=name,170                category=category,171                category_raw=slug.replace("-", " "),172                size_label=size_m.group(1) if size_m else "",173                price=price,174                in_stock=in_stock,175                details={"item_number": pid},176                images=[img["src"]] if img is not None else [],177            ))178        return products179180    # -- contrat ---------------------------------------------------------------181    def fetch(self) -> list[Product]:182        products: list[Product] = []183        seen: set[str] = set()184        for slug, category in CATEGORIES:185            url = f"https://www.costco.ca/{slug}.html"186            try:187                html = self.get_scrapfly(188                    url, render_js=True,189                    wait_for_selector='[data-testid^="ProductTile"]',190                    must_contain="ProductTile_",191                    accept=lambda h, c=category, s=slug: bool(self._parse(h, c, s)))192            except Exception:   # une catégorie qui casse ne bloque pas le reste193                continue194            for prod in self._parse(html, category, slug):195                if prod.uid not in seen:196                    seen.add(prod.uid)197                    products.append(prod)198        return products199
Files main
Menu

Theme