SPB Git

Repository Public

via_capitale.py 13.0 KB 320 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/via_capitale.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-1213# Last Modified    : 2026-08-2714#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# Lou-Ka — Agrégateur de logements à louer (province de Québec)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# connectors/via_capitale.py : Via Capitale (viacapitalevendu.com) — LOCATIONS91#   Bannière 100 % québécoise (Bridgemarq). Le site est rendu serveur (ASP.NET)92#   mais protégé par Cloudflare : on passe par le rendu Scrapfly (get_rendered, ex-Firecrawl) qui93#   franchit le challenge — testé : Scrapfly ASP passe Cloudflare mais ne rend94#   pas les cartes. La recherche accepte un blob base64 `criteresJson` ;95#   « AVendre »: false y bascule le même moteur en mode LOCATION (prix96#   « X $ / mois », ~34 cartes/page). Adapté du connecteur « à vendre »97#   d'Immo-Ka (agent-courtage/immoka).98# -----------------------------------------------------------------------------99from __future__ import annotations100101import base64102import html as _htmlmod103import json104import os105import re106107from .base import BaseConnector108from . import _detailutil as du109from ..schema import Listing, parse_price110111DETAIL_LIMIT = int(os.environ.get("LOUKA_VC_DETAIL_LIMIT", "150"))112_FICHE_IMG_RE = re.compile(113    r'images\.viacapitale\.info/images/inscriptions/(\d+)/([^"\'?)\s]+)', re.I)114115SITE = "https://www.viacapitalevendu.com"116SEARCH = f"{SITE}/recherche/residentiel/"117MAX_PAGES = int(os.environ.get("LOUKA_VC_MAX_PAGES", "40"))118119# La pagination du portail n'est active QUE si `criteresJson` est présent.120# Blob = critères vides + « AVendre »: false (= locations seulement) —121# construit au chargement pour rester lisible/modifiable.122_CRITERES = {123    "Caracteristiques": [], "AutresCritere": [], "TypeDePropriete": [],124    "TypeDeBatiment": None, "PeriodesAffichage": None, "AnneeDeConstruction": None,125    "Region": None, "NomRegion": None, "NombreDeChambre": 0, "NombreDeBain": 0,126    "PrixMinimum": "0", "PrixMaximum": "0",127    "PrixLocationMinimum": "0", "PrixLocationMaximum": "0",128    "OrderBy": None, "Type": 0, "AVendre": False,129    "FromAfficherToutesPropriete": False,130    "SuperficieMinimum": "", "SuperficieMaximum": "", "UniteMesure": "PC",131    "MotsCles": None, "Zonage": None, "NombreUnites": 1,132    "SuccursaleCode": None, "AgenceCode": None, "MembreCode": None,133    "EquipeId": 0, "SuccursaleName": None, "AgenceName": None,134    "MembreName": None, "EquipeName": None, "inputRegions": None,135    "ReturnUrl": None, "Latitude": None, "Longitude": None,136    "NoInscriptionNonDispo": None, "EnRecherche": False,137    "PlusDeCriteres": "false", "Specialite": None,138    "NomPlanEau": None, "NomPlanEauMobile": None,139    "IdPlanEau": None, "IdPlanEauMobile": 0,140    "GenrePropreteFrUrl": None, "GenreProprieteFrUrl": None,141    "GenreProprieteEnUrl": None, "selecPAMobile": None,142    "selecCaracMobile": [None] * 10, "selecACMobile": [None] * 10,143    "selecTBMobile": [None] * 10,144}145CRITERES_JSON = base64.b64encode(146    json.dumps(_CRITERES, separators=(",", ":")).encode()).decode()147IMG_HOST = "https://images.viacapitale.info"148149# Un bloc-carte commence à un lien vers une fiche d'inscription horodatée150# le rendu Scrapfly sérialise les hrefs en RELATIF (Firecrawl donnait151# l'absolu) : on accepte les deux formes, groupe 1 = chemin relatif152CARD_SPLIT = re.compile(153    r'<a href="(?:https://www\.viacapitalevendu\.com)?(/[^"]*?-(\d{6,}))"')154PRICE_RE = re.compile(r'class="price">\s*([\d   ]+\$\s*/\s*mois)', re.I)155ADDR_RE = re.compile(r'addressListe[^>]*>\s*<a[^>]*title="([^"]+)"', re.I)156IMG_RE = re.compile(r'images\.viacapitale\.info/images/inscriptions/(\d+)/([^"?)\s]+)', re.I)157TYPE_RE = re.compile(158    r'(Appartement|Condo[\w\s]*|Maison[\w\s\-àâéèêëîïôûùç]*|Duplex|Triplex|'159    r'Quadruplex|Loft|Studio|Maison de ville|Jumelé|Chalet)', re.I)160_PAREN = re.compile(r"\(([^)]*)\)")161162163def _unescape(s: str) -> str:164    return _htmlmod.unescape(s).replace("\xa0", " ").replace("&nbsp;", " ").strip()165166167def _split_addr(full: str) -> tuple[str, str, str]:168    """« 1455 Rue des Cèdres, Lévis (Les Chutes-de-la-Chaudière-Ouest) »169    -> (adresse, ville, secteur)."""170    if not full:171        return "", "", ""172    parts = [p.strip() for p in full.split(",", 1)]173    address = parts[0]174    city = sector = ""175    if len(parts) > 1:176        muni = parts[1]177        parens = _PAREN.findall(muni)178        city = _PAREN.sub("", muni).strip()179        if parens:180            sector = parens[-1].strip()181    return address, city, sector182183184# slug ex. « saguenay-lac-saint-jean-sainte-hedwidge-ch-de-la-lievre-… »185_REGIONS = (186    "bas-saint-laurent", "saguenay-lac-saint-jean", "capitale-nationale",187    "mauricie", "estrie", "montreal", "outaouais", "abitibi-temiscamingue",188    "cote-nord", "nord-du-quebec", "gaspesie-iles-de-la-madeleine",189    "chaudiere-appalaches", "laval", "lanaudiere", "laurentides",190    "monteregie", "centre-du-quebec",191)192193194def _from_slug(url: str) -> tuple[str, str]:195    tail = url.rstrip("/").rsplit("/", 1)[-1]196    for reg in _REGIONS:197        if tail.startswith(reg):198            rest = tail[len(reg) + 1:]199            city = rest.split("-")[0].replace("-", " ").title() if rest else ""200            return reg.replace("-", " ").title(), city201    return "", ""202203204class ViaCapitaleConnector(BaseConnector):205    source_id = "via_capitale"206207    def fetch(self) -> list[Listing]:208        by_id: dict[str, Listing] = {}209        empty_streak = 0210        for page in range(1, MAX_PAGES + 1):211            url = f"{SEARCH}?page={page}&criteresJson={CRITERES_JSON}"212            # Cloudflare renvoie parfois un challenge/vide par intermittence :213            # on retente la page une fois avant de la considérer vraiment vide.214            cards = []215            for _attempt in range(2):216                try:217                    html = self.get_rendered(url)218                except Exception:219                    html = ""220                cards = self._parse_cards(html)221                if cards:222                    break223            new = 0224            for lst in cards:225                if lst.uid not in by_id:226                    by_id[lst.uid] = lst227                    new += 1228            if not cards or new == 0:229                empty_streak += 1230                if empty_streak >= 3:231                    break232            else:233                empty_streak = 0234        listings = list(by_id.values())235        # fiche détail (requête simple, hors Cloudflare) : galerie + description236        du.enrich(self, listings, DETAIL_LIMIT, parse_vc_detail, key="v1")237        return listings238239    def _parse_cards(self, html: str) -> list[Listing]:240        # découpe la page en segments, un par carte (lien fiche + id)241        matches = list(CARD_SPLIT.finditer(html))242        out = []243        for i, m in enumerate(matches):244            url, code = m.group(1), m.group(2)245            seg = html[m.start(): matches[i + 1].start() if i + 1 < len(matches)246                       else m.start() + 2500]247            out.append(self._to_listing(url, code, seg))248        return [x for x in out if x]249250    def _to_listing(self, url: str, code: str, seg: str) -> Listing | None:251        price_m = PRICE_RE.search(seg)252        if not price_m:253            return None        # pas de « $ / mois » = pas une location rendue254        price_label = _unescape(price_m.group(1))255        addr_m = ADDR_RE.search(seg)256        address_full = _unescape(addr_m.group(1).strip()) if addr_m else ""257        type_m = TYPE_RE.search(re.sub(r"<[^>]+>", " ", seg))258        prop_type = (re.split(r"\s{2,}|\n", type_m.group(1))[0].strip()259                     if type_m else "")260261        address, city, sector = _split_addr(address_full)262263        images = []264        for im in IMG_RE.finditer(seg):265            u = f"{IMG_HOST}/images/inscriptions/{im.group(1)}/{im.group(2)}"266            if u not in images:267                images.append(u)268269        region, city_slug = _from_slug(url)270        details = {"Courtier": "Via Capitale"}271        if region:272            details["Région"] = region273        if prop_type:274            details["Type"] = prop_type275        unit_type = prop_type if prop_type.lower() in ("studio", "loft") else ""276        return Listing(277            source=self.source_id,278            external_id=code,279            url=f"{SITE}/inscription/fichedescriptive/?code={code}",280            title=f"{prop_type} — {address}".strip(" —") or address_full,281            address=address,282            city=city or city_slug,283            sector=sector,284            unit_type=unit_type,285            price=parse_price(price_label),286            price_label=price_label,287            details=details,288            images=images,289        )290291292def parse_vc_detail(html: str) -> dict:293    """Fiche Via Capitale : galerie complète + description (plus long bloc)."""294    out: dict = {}295    seen, imgs = set(), []296    for m in _FICHE_IMG_RE.finditer(html):297        u = f"{IMG_HOST}/images/inscriptions/{m.group(1)}/{m.group(2)}"298        if u not in seen:299            seen.add(u)300            imgs.append(u)301    if imgs:302        out["images"] = imgs303    # description = plus long bloc de texte visible (marketing de la propriété)304    best = ""305    for b in re.findall(r"<div[^>]*>(.*?)</div>", html, re.S):306        txt = re.sub(r"\s+", " ", _htmlmod.unescape(re.sub(r"<[^>]+>", " ", b))).strip()307        if len(txt) > len(best) and "window" not in txt and "function" not in txt \308                and "{" not in txt:309            best = txt310    if len(best) > 120:311        out["description"] = best[:4000]312    det = du.centris_details(du.flatten(html))313    if det:314        out["details"] = det315        # « Nombre de pièces : 4 pièces » → unité normalisable (4½ etc.)316        pieces = det.get("Nombre de pièces")317        if pieces:318            out["unit_type"] = pieces319    return out320
Files main
Menu

Theme