SPB Git

Repository Public

occasioncharlevoix.py 11.4 KB 294 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Auto·Ka9# File             : autoka/connectors/occasioncharlevoix.py10# Module           : autoka11# Repository       : https://git.spboucher.ai/auto-ka12# Created          : 2026-08-1213# 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/occasioncharlevoix.py : connecteur Occasion Charlevoix91#   (occasioncharlevoix.com), regroupement de concessionnaires d'occasion de92#   Baie-Saint-Paul (Charlevoix, Capitale-Nationale) — ~30 véhicules.93#94#   Plateforme : OctoberCMS, thème « nerd2 » + plugins nerd/inventory95#   (plateforme québécoise NerdAuto). La page liste /fr/inventaire/occasion96#   est ENTIÈREMENT rendue côté serveur : chaque carte (div.vrp4-card)97#   contient marque, modèle, version, année, no de stock, kilométrage, photos98#   (carrousel) et un bloc « Autoverify » (div.av-srp-ecomm) avec VIN et prix99#   réel (data-av-price — le prix affiché en gros est un paiement périodique).100#101#   La page détail complète (cache BD, clé statique v1) : transmission,102#   cylindrée, motricité, couleurs, catégorie, lien Carfax.103# -----------------------------------------------------------------------------104from __future__ import annotations105106import os107import re108109from ..schema import Vehicle, parse_mileage110from .base import BaseConnector111112# garde-fou non-automobile113_EXCLUDE_RE = re.compile(114    r"motoneige|vtt|moto\b|motomarine|bateau|roulotte|remorque|spyder", re.I)115116_SPEC_RE = re.compile(117    r'class="specs-name[^"]*">\s*([^<]+?)\s*</div>\s*'118    r'<div class="specs-info[^"]*">\s*([^<]*?)\s*<', re.S)119120_CARFAX_RE = re.compile(r'data-lien-carfax="([^"]+)"')121# repli : lien direct vhr.carfax.ca rendu ailleurs dans la page (vérifié122# 2026-08 : ~55 % des fiches ont data-lien-carfax ; les autres n'exposent123# aucun rapport — le bloc Autoverify data-av-* ne porte que VIN/prix/km)124_CARFAX_VHR_RE = re.compile(r'https?://vhr\.carfax\.ca/[^\s"\'<>\\]+', re.I)125126_AV_DETAIL_RE = re.compile(127    r'id="av_vehicle_information"[^>]*data-av-mileage="([^"]*)"')128129130def _txt(node) -> str:131    return re.sub(r"\s+", " ", node.get_text(" ", strip=True)) if node else ""132133134class OccasionCharlevoix(BaseConnector):135    """Occasion Charlevoix — cartes liste rendues serveur (OctoberCMS nerd)."""136137    source_id = "occasioncharlevoix"138    base_url = "https://www.occasioncharlevoix.com"139    dealer_name = "Occasion Charlevoix"140    city = "Baie-Saint-Paul"141    request_delay = 1.0142    max_details = 200143144    def fetch(self) -> list[Vehicle]:145        from bs4 import BeautifulSoup146        cap = int(os.environ.get("AUTOKA_MAX_DETAILS", self.max_details))147        html = self.get(f"{self.base_url}/fr/inventaire/occasion").text148        soup = BeautifulSoup(html, "html.parser")149150        vehicles: list[Vehicle] = []151        seen: set[str] = set()152        real_fetches = 0153        for card in soup.select("div.vrp4-card"):154            try:155                veh = self._card_to_vehicle(card)156            except Exception:157                continue                     # carte malformée isolée158            if veh is None or veh.external_id in seen:159                continue160            seen.add(veh.external_id)161162            # enrichissement page détail (transmission, couleurs, carfax…)163            if real_fetches < cap:164                url = veh.url165166                def _fetch(u=url):167                    return self._fetch_detail(u)168169                try:170                    extra = self.detail(veh.external_id, "v1", _fetch)171                    real_fetches += 1172                    self._apply_detail(veh, extra)173                except Exception:174                    real_fetches += 1        # ne jamais bloquer la source175            vehicles.append(veh)176        return vehicles177178    # -- carte liste -> Vehicle -------------------------------------------------179    def _card_to_vehicle(self, card) -> Vehicle | None:180        link = card.select_one("a.vrp4-card-header[href]")181        if link is None:182            return None183        url = link["href"]184        if "/inventaire/vehicule/" not in url:185            return None186        if url.startswith("/"):187            url = self.base_url + url188189        # /fr/inventaire/vehicule/occasion/<stock>/<marque>/<modèle>/…190        m = re.search(r"/vehicule/[^/]+/([^/]+)/", url)191        ext_id = m.group(1) if m else url.rstrip("/").rsplit("/", 1)[-1]192193        make = _txt(card.select_one(".car-make"))194        model = _txt(card.select_one(".car-model"))195        trim = _txt(card.select_one(".car-trim"))196        if _EXCLUDE_RE.search(f"{make} {model} {trim}"):197            return None198199        year_txt = _txt(card.select_one(".car-year"))200        year = int(year_txt) if year_txt.isdigit() else None201202        stock = _txt(card.select_one(".car-stock")).lstrip("#")203        odo_label = _txt(card.select_one(".car-odometer"))204        km = parse_mileage(odo_label)205206        # bloc Autoverify : VIN + prix réel (le prix visible est un paiement)207        vin, price = "", None208        av = card.select_one(".av-srp-ecomm")209        if av is not None:210            vin = (av.get("data-av-vin") or "").strip().upper()211            try:212                price = float(av.get("data-av-price") or 0) or None213            except ValueError:214                price = None215            # garde-fou : < 1 500 $ = paiement périodique saisi comme prix216            if price is not None and price < 1500:217                price = None218219        images = []220        for img in card.select("img.car-img[src]"):221            src = img["src"]222            if src.startswith("/"):223                src = self.base_url + src224            if src not in images:225                images.append(src)226227        title = " ".join(x for x in (make, model, trim, year_txt) if x)228        if not title:229            return None230231        return Vehicle(232            source=self.source_id,233            external_id=ext_id,234            url=url,235            title=title,236            make=make,237            model=model,238            trim=trim,239            year=year,240            price=price,241            price_label=f"{price:,.0f} $".replace(",", " ") if price else "",242            mileage_km=km,243            mileage_label=odo_label,244            vin=vin,245            stock_number=stock or ext_id.upper(),246            dealer_name=self.dealer_name,247            city=self.city,248            images=images[:20],249        )250251    # -- page détail -------------------------------------------------------------252    def _fetch_detail(self, url: str) -> dict:253        html = self.get(url).text254        payload: dict = {"specs": {}}255        for name, value in _SPEC_RE.findall(html):256            payload["specs"][name.rstrip(": ").strip()] = value.strip()257        m = _CARFAX_RE.search(html)258        if m:259            payload["carfax"] = m.group(1)260        else:261            m = _CARFAX_VHR_RE.search(html)262            if m:263                payload["carfax"] = m.group(0)264        m = _AV_DETAIL_RE.search(html)265        if m and m.group(1):266            payload["mileage"] = m.group(1)267        return payload268269    def _apply_detail(self, veh: Vehicle, extra: dict) -> None:270        specs = (extra or {}).get("specs") or {}271        for name, value in specs.items():272            low = name.lower()273            if not value or value.lower() in ("autre", "n/d", "s/o"):274                continue275            if "transmission" in low and not veh.transmission:276                veh.transmission = value277            elif "motricit" in low and not veh.drivetrain:278                veh.drivetrain = value279            elif "cat" in low and not veh.body_type:280                veh.body_type = value281            elif "cylindr" in low and not veh.engine:282                veh.engine = value283            elif "ext" in low and "couleur" in low and not veh.exterior_color:284                veh.exterior_color = value285            elif "int" in low and "couleur" in low and not veh.interior_color:286                veh.interior_color = value287        if extra.get("carfax") and not veh.carfax_url:288            veh.carfax_url = extra["carfax"]289        if veh.mileage_km is None and extra.get("mileage"):290            try:291                veh.mileage_km = float(extra["mileage"])292            except ValueError:293                pass294
Files main
Menu

Theme