Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Auto·Ka9# File : autoka/connectors/kijiji.py10# Module : autoka11# Repository : https://git.spboucher.ai/auto-ka12# Created : 2026-08-1813# Last Modified : 2026-08-1814#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# Auto-Ka — Agrégateur de voitures usagées à vendre (province de Québec)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# connectors/kijiji.py : annonces de PARTICULIERS — Kijiji (kijiji.ca)91#92# Note : Kijiji Autos (kijijiautos.ca, plateforme MoVe/m.mobile.de) n'existe93# plus — le domaine ne résout plus (SERVFAIL, constaté 2026-08-18) ; les94# annonces ont été rapatriées sur kijiji.ca. On cible donc la catégorie95# « Autos et camions » (c174) du Québec (l9001), filtrée vendeur particulier96# (?for-sale-by=ownr) pour ne pas dupliquer l'inventaire des concessionnaires97# déjà couverts par les autres connecteurs.98#99# Stratégie : les pages liste (SRP) de kijiji.ca (Next.js) embarquent le100# cache Apollo complet dans <script id="__NEXT_DATA__"> — chaque annonce y101# est un objet AutosListing structuré : marque/modèle/année/km canoniques,102# prix (en cents), carburant/boîte/rouage/carrosserie, couleurs, portes,103# places, VIN (quand le vendeur l'a saisi), lien Carfax, photos CDN et104# surtout la géolocalisation exacte (lat/lng + adresse). Aucune page détail105# n'est nécessaire : tout est dans la liste — 40 annonces/requête.106#107# Pagination : /b-autos-camions/quebec/page-N/c174l9001?for-sale-by=ownr108# jusqu'à totalCount (bornée par MAX_PAGES par politesse).109# -----------------------------------------------------------------------------110from __future__ import annotations111112import json113import re114115from ..schema import Vehicle116from .base import BaseConnector117118BASE = "https://www.kijiji.ca"119LIST_PATH = "/b-autos-camions/quebec/{page}c174l9001?for-sale-by=ownr"120121_NEXT_DATA_RE = re.compile(122 r'<script id="__NEXT_DATA__" type="application/json">(.*?)</script>', re.S)123124# suffixes d'adresse à écarter pour isoler la ville : « QC », code postal125# complet ou partiel (« J7V »), ou les deux (« QC H7X 2S6 »)126_ADDR_TAIL_RE = re.compile(127 r"^(?:QC|Qc|Qu[ée]bec)?\s*(?:[A-Za-z]\d[A-Za-z](?:\s?\d[A-Za-z]\d)?)?$")128129# grandes photos plutôt que les vignettes 200 px de la liste130_IMG_RULE_RE = re.compile(r"rule=kijijica-\d+-")131132# valeurs canoniques Kijiji -> vocabulaire Auto-Ka (normalize.py gère le reste)133_TRANSMISSIONS = {"1": "Manuelle", "2": "Automatique", "3": "",134 "auto": "Automatique", "man": "Manuelle"}135_BODIES = {"sedan": "Berline", "suvcrossover": "VUS", "htchbck": "Hayon",136 "conv": "Cabriolet", "coup": "Coupé", "pickuptruck": "Camionnette",137 "vanminicomma": "Fourgonnette", "wagon": "Familiale",138 "othrbdytyp": ""}139_COLORS = {"white": "Blanc", "black": "Noir", "gray": "Gris", "grey": "Gris",140 "silver": "Argent", "blue": "Bleu", "red": "Rouge", "brown": "Brun",141 "green": "Vert", "burgundy": "Bourgogne", "gold": "Doré",142 "orange": "Orange", "off_white": "Blanc cassé", "beige": "Beige",143 "tan": "Beige", "yellow": "Jaune", "purple": "Violet",144 "other": ""}145146MAX_PAGES = 90 # 90 × 40 = 3 600 annonces — couvre le volume QC actuel147PAGE_SIZE = 40148149150def _attr_map(listing: dict) -> dict[str, str]:151 out: dict[str, str] = {}152 for a in ((listing.get("attributes") or {}).get("all") or []):153 vals = a.get("canonicalValues") or []154 if vals and vals[0] is not None:155 out[a.get("canonicalName") or ""] = str(vals[0])156 return out157158159def _city_from_location(loc: dict) -> str:160 """Ville depuis l'adresse — formats observés : « Rue X, Laval, QC H7X 2S6 »,161 « Vaudreuil-Dorion, QC J7V », « Anjou, QC H1J 2W1 », « Laval, H7Y 2B7 »."""162 parts = [p.strip() for p in (loc.get("address") or "").split(",") if p.strip()]163 # retirer depuis la fin : « QC », code postal (complet/partiel) ou les deux164 while parts and _ADDR_TAIL_RE.match(parts[-1]):165 parts.pop()166 if parts:167 return parts[-1]168 # repli : nom de zone Kijiji (« Laval / North Shore » -> Laval)169 return ((loc.get("name") or "").split("/")[0]).strip()170171172class KijijiParticuliers(BaseConnector):173 """Annonces de particuliers — Kijiji, catégorie Autos et camions, Québec."""174175 source_id = "kijiji"176 request_delay = 1.2 # politesse : gros site, gros volume177178 def __init__(self) -> None:179 super().__init__()180 self.session.headers.update({181 "Accept": "text/html,application/xhtml+xml",182 "Accept-Language": "fr-CA,fr;q=0.9,en;q=0.5",183 })184185 # -- extraction -----------------------------------------------------------186187 def _fetch_page(self, page: int) -> tuple[list[dict], int]:188 """Annonces AutosListing + totalCount d'une page SRP."""189 seg = "" if page <= 1 else f"page-{page}/"190 html = self.get(BASE + LIST_PATH.format(page=seg)).text191 m = _NEXT_DATA_RE.search(html)192 if not m:193 raise RuntimeError(f"kijiji : __NEXT_DATA__ introuvable (page {page})")194 data = json.loads(m.group(1))195 apollo = (data.get("props", {}).get("pageProps", {})196 .get("__APOLLO_STATE__") or {})197 total = 0198 for key, val in (apollo.get("ROOT_QUERY") or {}).items():199 if key.startswith("searchResultsPageByUrl"):200 total = int((val.get("pagination") or {}).get("totalCount") or 0)201 break202 listings = [v for k, v in apollo.items()203 if k.startswith("AutosListing:") and isinstance(v, dict)]204 return listings, total205206 def _to_vehicle(self, l: dict) -> Vehicle | None:207 ext_id = str(l.get("id") or "")208 if not ext_id:209 return None210 attrs = _attr_map(l)211 if attrs.get("forsaleby") not in ("", "ownr"):212 return None # topListings = pubs de marchands213 if attrs.get("vehicletype") == "new":214 return None # occasion seulement215216 price = None217 p = l.get("price") or {}218 if p.get("type") == "FIXED" and p.get("amount"):219 price = round(p["amount"] / 100.0, 2)220 if price < 500: # « 1 $ » = prix symbolique de petite annonce221 price = None222223 loc = l.get("location") or {}224 coords = loc.get("coordinates") or {}225 images = [_IMG_RULE_RE.sub("rule=kijijica-640-", u)226 for u in (l.get("imageUrls") or [])]227228 km = None229 if attrs.get("carmileageinkms", "").replace(".", "", 1).isdigit():230 km = float(attrs["carmileageinkms"])231232 def _int(name: str) -> int | None:233 v = attrs.get(name, "")234 return int(v) if v.isdigit() else None235236 details = {"forsaleby": "particulier"}237 if l.get("activationDate"):238 details["posted"] = l["activationDate"][:10]239 if attrs.get("pricerating"):240 details["kijiji_price_rating"] = attrs["pricerating"]241 if attrs.get("electricrange", "").replace(".", "", 1).isdigit():242 details["electric_range_km"] = float(attrs["electricrange"])243244 vin = attrs.get("vin", "").strip().upper()245 if not re.fullmatch(r"[A-HJ-NPR-Z0-9]{17}", vin):246 vin = ""247248 veh = Vehicle(249 source=self.source_id,250 external_id=ext_id,251 url=l.get("url") or f"{BASE}/v-view-details.html?adId={ext_id}",252 kind="auto",253 title=l.get("title") or "",254 make=attrs.get("carmake", ""),255 model=attrs.get("carmodel", "").capitalize(),256 trim=attrs.get("cartrim", ""),257 year=_int("caryear"),258 price=price,259 price_label=(f"{price:,.0f} $".replace(",", " ") if price else ""),260 mileage_km=km,261 transmission=_TRANSMISSIONS.get(attrs.get("cartransmission", ""),262 attrs.get("cartransmission", "")),263 fuel=("" if attrs.get("carfueltype") == "other"264 else attrs.get("carfueltype", "")),265 drivetrain=("" if attrs.get("drivetrain") == "other"266 else attrs.get("drivetrain", "")),267 body_type=_BODIES.get(attrs.get("carbodytype", ""),268 attrs.get("carbodytype", "")),269 exterior_color=_COLORS.get(attrs.get("carcolor", ""),270 attrs.get("carcolor", "").capitalize()),271 interior_color=_COLORS.get(attrs.get("carinteriorcolor", ""),272 attrs.get("carinteriorcolor", "").capitalize()),273 doors=_int("noofdoors"),274 seats=_int("noofseats"),275 vin=vin,276 dealer_name="Particulier (Kijiji)",277 city=_city_from_location(loc),278 lat=coords.get("latitude"),279 lng=coords.get("longitude"),280 description=l.get("description") or "",281 details=details,282 images=images,283 carfax_url=attrs.get("carprooflink", ""),284 )285 return veh286287 # -- contrat ---------------------------------------------------------------288289 def fetch(self) -> list[Vehicle]:290 vehicles: dict[str, Vehicle] = {}291 listings, total = self._fetch_page(1)292 pages = min(MAX_PAGES, -(-max(total, 1) // PAGE_SIZE))293 for l in listings:294 v = self._to_vehicle(l)295 if v:296 vehicles[v.external_id] = v297 for page in range(2, pages + 1):298 try:299 listings, _ = self._fetch_page(page)300 except Exception:301 break # fin de pagination / page vide302 new = 0303 for l in listings:304 v = self._to_vehicle(l)305 if v and v.external_id not in vehicles:306 vehicles[v.external_id] = v307 new += 1308 if new == 0: # au-delà de la dernière page309 break310 return list(vehicles.values())311