SPB Git

Repository Public

walmart.py 9.0 KB 215 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Food·Ka9# File             : foodka/connectors/walmart.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 Walmart Canada (walmart.ca, rayon épicerie)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# Site Next.js derrière Akamai/PerimeterX (curl direct → HTTP 418) : on lit la91# grille produits embarquée dans <script id="__NEXT_DATA__"> via Scrapfly ASP92# (pas de rendu JavaScript nécessaire — le JSON est côté serveur).93# URLs de rayon : /fr/browse/epicerie/{slug}/10019_{id} — seul l'id compte,94# le slug est décoratif ; pagination par ?page=N (55 produits/page).95# -----------------------------------------------------------------------------96from __future__ import annotations9798import json99import re100101from ..schema import Product, parse_price102from .base import BaseConnector103104_NEXT_RE = re.compile(105    r'<script id="__NEXT_DATA__" type="application/json"[^>]*>(.*?)</script>',106    re.S)107# format dans le nom du produit : "567 g", "2 L", "12 x 355 ml"…108_SIZE_IN_NAME = re.compile(109    r"((?:\d+\s*[x×]\s*)?\d+(?:[.,]\d+)?\s*(?:kg|g|ml|l|lb|oz|un))\b",110    re.IGNORECASE)111112# rayons épicerie Walmart : (slug décoratif, id de catégorie, catégorie canonique)113CATEGORIES = [114    ("fruits-et-legumes-frais", "6000194327370", "Fruits et légumes"),115    ("charcuteries-et-repas-prepares", "6000194327356", "Charcuteries et fromages"),116    ("produits-laitiers-oeufs", "6000194327369", "Produits laitiers et œufs"),117    ("pains-et-boulangerie", "6000194327359", "Boulangerie"),118    ("aliments-surgeles", "6000194326337", "Surgelés"),119    ("garde-manger", "6000194326346", "Garde-manger"),120    ("boissons", "6000194326336", "Boissons"),121    ("collations-bonbons", "6000194328523", "Collations et confiseries"),122]123124125class WalmartConnector(BaseConnector):126    source_id = "walmart"127    pages_per_category = 2   # 55 produits/page → ~880 produits/sync128129    # -- récupération ----------------------------------------------------------130    def _items(self, url: str) -> list[dict]:131        """Tuiles produit d'une page de rayon (JSON __NEXT_DATA__)."""132        html = self.get_scrapfly(url, must_contain="__NEXT_DATA__")133        m = _NEXT_RE.search(html)134        if not m:135            return []136        data = json.loads(m.group(1))137        try:138            sr = data["props"]["pageProps"]["initialData"]["searchResult"]139        except (KeyError, TypeError):140            return []141        items: list[dict] = []142        for stack in sr.get("itemStacks") or []:143            items.extend(stack.get("items") or [])144        return items145146    # -- transformation --------------------------------------------------------147    def _item_to_product(self, item: dict, category: str) -> Product | None:148        if item.get("__typename") not in (None, "Product"):149            return None150        pid = item.get("usItemId") or item.get("id")151        name = item.get("name") or ""152        if not pid or not name:153            return None154        info = item.get("priceInfo") or {}155        # `price` est le prix courant numérique ; linePrice le libellé affiché156        price = parse_price(item.get("price"))157        if price is None:158            price = parse_price(info.get("linePrice"))159        was = parse_price(info.get("wasPrice"))160        link = item.get("canonicalUrl") or ""161        image = (item.get("imageInfo") or {}).get("thumbnailUrl") \162            or item.get("image") or ""163        cat_path = [p.get("name") for p in164                    ((item.get("category") or {}).get("path") or [])165                    if isinstance(p, dict) and p.get("name")]166        size_m = _SIZE_IN_NAME.search(name)167        out_of_stock = item.get("isOutOfStock")168        return Product(169            source=self.source_id,170            external_id=str(pid),171            url=f"https://www.walmart.ca{link}" if link.startswith("/") else link,172            name=name,173            brand=item.get("brand") or "",174            category=category,175            category_raw=" > ".join(cat_path),176            size_label=size_m.group(1) if size_m else "",177            price=price,178            regular_price=was,179            price_label=info.get("linePriceDisplay") or info.get("linePrice") or "",180            on_sale=bool(was and price and was > price),181            in_stock=(not out_of_stock) if out_of_stock is not None else None,182            unit_price_label=info.get("unitPrice") or "",183            details={"sales_unit": item.get("salesUnitType"),184                     "seller": item.get("sellerName")},185            images=[image] if image else [],186        )187188    # -- contrat ---------------------------------------------------------------189    def fetch(self) -> list[Product]:190        products: list[Product] = []191        seen: set[str] = set()192        for slug, cat_id, category in CATEGORIES:193            for page in range(1, self.pages_per_category + 1):194                url = (f"https://www.walmart.ca/fr/browse/epicerie/"195                       f"{slug}/10019_{cat_id}?page={page}")196                try:197                    items = self._items(url)198                except Exception:   # un rayon qui casse ne bloque pas le reste199                    break200                if not items:201                    break202                new = 0203                for item in items:204                    try:205                        prod = self._item_to_product(item, category)206                    except Exception:207                        continue208                    if prod and prod.uid not in seen:209                        seen.add(prod.uid)210                        products.append(prod)211                        new += 1212                if new == 0:   # page sans nouveauté = fin du rayon213                    break214        return products215
Files main
Menu

Theme