Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Auto·Ka9# File : autoka/connectors/cargurus.py10# Module : autoka11# Repository : https://git.spboucher.ai/auto-ka12# Created : 2026-08-1813# Last Modified : 2026-09-1314#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/cargurus.py : PORTAIL — CarGurus.ca (Québec, avec « deal rating »)91#92# CarGurus est protégé par DataDome (403 en direct, page « enable JS »).93# MAIS son API interne de liste répond en JSON pur à travers Scrapfly ASP94# SANS render_js — coût observé : 1 crédit/requête (proxy datacenter) :95# GET /Cars/searchResults.action?zip=H2X1Y4&distance=50096# &entitySelectingHelper.selectedEntity=&offset=N&maxResults=5097# &sortDir=ASC&sortType=AGE_IN_DAYS&filtersModified=true98# → tableau JSON de ~48 annonces ultra-riches : VIN (≈100 % — alimente la99# dédup inter-sources), prix + PRIX ATTENDU + dealRating/dealScore100# (l'évaluation « bonne/mauvaise affaire » maison de CarGurus, stockée101# dans details), km, boîte, carburant, rouage, carrosserie, couleurs,102# moteur, équipements, concessionnaire + ville + téléphone, photo.103#104# Rayon : zip Montréal (H2X 1Y4) + distance=500 km couvre tout le Québec ;105# les débordements ON/NB sont filtrés par sellerRegion == "QC".106# Tri : AGE_IN_DAYS ASC = plus récentes d'abord — fenêtre glissante.107#108# Budget SERRÉ (documenté) : plafond AUTOKA_CARGURUS_MAX (défaut 500)109# → ~11 requêtes ≈ 11 crédits Scrapfly par sync, ~130/jour au rythme110# de 12 syncs/jour. Les annonces sorties de la fenêtre passent inactives111# après le délai de grâce standard (MISS_GRACE).112# -----------------------------------------------------------------------------113from __future__ import annotations114115import json116import os117import re118119from ..schema import Vehicle120from .base import BaseConnector121122API = ("https://www.cargurus.ca/Cars/searchResults.action"123 "?zip=H2X1Y4&distance=500&entitySelectingHelper.selectedEntity="124 "&offset={offset}&maxResults=50"125 "&sortDir=ASC&sortType=AGE_IN_DAYS&filtersModified=true")126127VDP = "https://www.cargurus.ca/Cars/inventorylisting/vdp.action?listingId={id}"128129MAX_OFFSET_SITE = 5000 # garde-fou de pagination130_VIN_RE = re.compile(r"^[A-HJ-NPR-Z0-9]{17}$")131_DOORS_RE = re.compile(r"(\d+)")132133134def _max_listings() -> int:135 try:136 return max(48, int(os.environ.get("AUTOKA_CARGURUS_MAX", "500")))137 except ValueError:138 return 500139140141class CarGurusQuebec(BaseConnector):142 """Portail CarGurus.ca — annonces QC récentes + deal rating (via Scrapfly)."""143144 source_id = "cargurus"145 request_delay = 1.0146147 # -- API ---------------------------------------------------------------------148149 def _fetch_batch(self, offset: int) -> list[dict]:150 """Un lot d'annonces JSON (via Scrapfly ASP, sans render_js).151152 L'ASP rate parfois un coup (contenu vide/HTML DataDome) et l'API153 Scrapfly elle-même a des micro-pannes (ConnectTimeout observé154 2026-09-13, deux syncs avortés en pleine pagination) : 2 nouvelles155 tentatives avant d'abandonner — coût borné à 3 crédits par lot156 (un échec de connexion ne consomme aucun crédit).157 """158 import time159160 import requests161162 last_exc: Exception | None = None163 for attempt in range(3):164 try:165 body = self.get_scrapfly(API.format(offset=offset),166 render_js=False, asp=True)167 data = json.loads(body)168 return data if isinstance(data, list) else []169 except (ValueError, requests.RequestException) as exc:170 last_exc = exc171 time.sleep(2.0 * (attempt + 1))172 raise RuntimeError(f"cargurus : échec à offset={offset} "173 f"({str(last_exc)[:80]})") from last_exc174175 def _to_vehicle(self, l: dict) -> Vehicle | None:176 ext_id = str(l.get("id") or "")177 if not ext_id:178 return None179 if (l.get("sellerRegion") or "") != "QC":180 return None # rayon 500 km : déborde sur ON/NB181182 price = l.get("price")183 price = float(price) if price else None184 mileage = l.get("mileage")185 mileage = float(mileage) if mileage is not None else None186187 vin = (l.get("vin") or "").strip().upper()188 if not _VIN_RE.fullmatch(vin):189 vin = ""190191 is_private = (l.get("sellerType") or "").upper() == "PRIVATE"192 dealer_name = (l.get("serviceProviderName") or "").strip()193 if is_private or not dealer_name:194 dealer_name = "Particulier (CarGurus)" if is_private else \195 "CarGurus.ca"196197 details: dict = {"forsaleby": "particulier" if is_private198 else "concessionnaire"}199 # l'évaluation d'aubaine maison de CarGurus — la valeur ajoutée du portail200 for src_key, dst_key in (("dealRating", "cargurus_deal_rating"),201 ("dealScore", "cargurus_deal_score"),202 ("expectedPrice", "cargurus_expected_price"),203 ("priceDifferential",204 "cargurus_price_differential"),205 ("daysOnMarket", "days_on_market")):206 if l.get(src_key) is not None:207 details[dst_key] = l[src_key]208 if l.get("phoneNumberString"):209 details["dealer_phone"] = l["phoneNumberString"]210211 doors = None212 m = _DOORS_RE.search(l.get("localizedDoors") or "")213 if m:214 doors = int(m.group(1))215216 city = (l.get("sellerCity") or "").split(",")[0].strip()217 img = (l.get("originalPictureData") or {}).get("url") or ""218219 return Vehicle(220 source=self.source_id,221 external_id=ext_id,222 url=VDP.format(id=ext_id),223 kind="auto",224 title=l.get("listingTitle") or "",225 make=l.get("makeName") or "",226 model=l.get("modelName") or "",227 trim=(l.get("trimName") or "").strip(),228 year=l.get("carYear"),229 price=price,230 price_label=(l.get("priceString") or "").strip(),231 mileage_km=mileage,232 transmission=l.get("localizedTransmission") or "",233 fuel=l.get("localizedFuelType") or "",234 drivetrain=l.get("localizedDriveTrain") or "",235 body_type=l.get("bodyTypeName") or "",236 exterior_color=l.get("localizedExteriorColor") or "",237 interior_color=l.get("localizedInteriorColor") or "",238 engine=l.get("localizedEngineDisplayName") or "",239 doors=doors,240 vin=vin,241 stock_number=l.get("stockNumber") or "",242 dealer_name=dealer_name,243 city=city,244 features=[o for o in (l.get("options") or []) if o],245 details=details,246 images=[img] if img else [],247 )248249 # -- contrat -----------------------------------------------------------------250251 def fetch(self) -> list[Vehicle]:252 cap = _max_listings()253 vehicles: dict[str, Vehicle] = {}254 offset = 0255 while len(vehicles) < cap and offset < MAX_OFFSET_SITE:256 batch = self._fetch_batch(offset)257 if not batch:258 break259 for l in batch:260 v = self._to_vehicle(l)261 if v and v.external_id not in vehicles:262 vehicles[v.external_id] = v263 offset += len(batch)264 return list(vehicles.values())265