SPB Git

Repository Public

via_capitale.py 17.8 KB 402 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Immo·Ka9# File             : immoka/connectors/via_capitale.py10# Module           : immoka11# Repository       : https://git.spboucher.ai/immo-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# Immo-Ka — Agrégateur de maisons à vendre (province de Québec)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# connectors/via_capitale.py : Via Capitale (viacapitalevendu.com)91#   Bannière 100 % québécoise (Bridgemarq). Le site est rendu serveur (ASP.NET)92#   mais protégé par Cloudflare : on passe donc par Firecrawl (get_rendered) qui93#   franchit le challenge. Les résultats résidentiels sont paginés (34/page,94#   ~5 300 propriétés). On parse les cartes HTML et on dédoublonne par code95#   d'inscription. Photos : images.viacapitale.info/images/inscriptions/{id}/…96# -----------------------------------------------------------------------------97from __future__ import annotations9899import html as _htmlmod2100import os101import re102103from .base import BaseConnector104from . import _detailutil as du105from ..normalize import parse_area_sqft, parse_price106from ..schema import PropertyListing107108# Fiche descriptive : la requête simple (UA ImmoKaBot) passe généralement,109# mais Cloudflare renvoie par intermittence un challenge 403 → repli Firecrawl110# (proxy stealth, crédits payants) ; budget par cycle volontairement modeste.111DETAIL_LIMIT = int(os.environ.get("IMMOKA_VIACAP_DETAIL_LIMIT", "200"))112_FICHE_IMG_RE = re.compile(r'images\.viacapitale\.info/images/inscriptions/(\d+)/([^"\'?)\s]+)', re.I)113# meta description de la fiche : « …à vendre 564 900$, 740 Route de St-Achillée.114#   2018, 5 chambres, 2 salle(s) de bain, Superficie 2324pi² »115_META_SPECS_RE = re.compile(116    r'(?:(\d{4}),\s*)?(\d+)\s*chambres?,\s*([\d.,]+)\s*salle\(s\) de bain'117    r'(?:,\s*Superficie\s*([\d\s  ]+)\s*pi²)?', re.I)118# tableau « Libellé | Valeur » de la fiche (texte aplati)119_VC_YEAR_RE = re.compile(r'Année de construction\s*\|\s*(\d{4})\b')120_VC_AREA_RE = re.compile(r'Superficie habitable\s*\|\s*([\d\s  ,.]+)\s*(pi²|m²|pc|mc)', re.I)121_VC_LOT_RE = re.compile(r'Superficie du terrain\s*\|\s*([\d\s  ,.]+)\s*(pi²|m²|pc|mc)', re.I)122_VC_MONEY = r'((?:\d[\d\s  ]*)\$)'123_VC_TAX_MUNI_RE = re.compile(r'Taxes municipales\s*(?:\((\d{4})\))?\s*\|\s*' + _VC_MONEY)124_VC_TAX_SCOL_RE = re.compile(r'Taxes scolaires\s*(?:\((\d{4})\))?\s*\|\s*' + _VC_MONEY)125# « Évaluations (2025) | Bâtiment | 304 300 $ | Terrain | 99 200 $ »126_VC_EVAL_RE = re.compile(127    r'Évaluations?\s*(?:\((\d{4})\))?\s*\|\s*Bâtiment\s*\|\s*' + _VC_MONEY +128    r'\s*\|\s*Terrain\s*\|\s*' + _VC_MONEY)129130SITE = "https://www.viacapitalevendu.com"131SEARCH = f"{SITE}/recherche/residentiel/"132MAX_PAGES = 200                       # garde-fou (~155 pages attendues)133# La pagination du portail n'est active QUE si le paramètre `criteresJson`134# (blob base64 des critères de recherche) est présent — sinon `?page=N` retombe135# toujours sur la 1re page. Ce blob = critères vides + « AVendre:true » ; il est136# statique et réutilisable pour parcourir les ~155 pages (~5 300 propriétés).137CRITERES_JSON = (138    "eyJDYXJhY3RlcmlzdGlxdWVzIjpbXSwiQXV0cmVzQ3JpdGVyZSI6W10sIlR5cGVEZVByb3ByaWV0ZSI6"139    "W10sIlR5cGVEZUJhdGltZW50IjpudWxsLCJQZXJpb2Rlc0FmZmljaGFnZSI6bnVsbCwiQW5uZWVEZUNv"140    "bnN0cnVjdGlvbiI6bnVsbCwiUmVnaW9uIjpudWxsLCJOb21SZWdpb24iOm51bGwsIk5vbWJyZURlQ2hh"141    "bWJyZSI6MCwiTm9tYnJlRGVCYWluIjowLCJQcml4TWluaW11bSI6IjAiLCJQcml4TWF4aW11bSI6IjAi"142    "LCJQcml4TG9jYXRpb25NaW5pbXVtIjoiMCIsIlByaXhMb2NhdGlvbk1heGltdW0iOiIwIiwiT3JkZXJC"143    "eSI6bnVsbCwiVHlwZSI6MCwiQVZlbmRyZSI6dHJ1ZSwiRnJvbUFmZmljaGVyVG91dGVzUHJvcHJpZXRl"144    "IjpmYWxzZSwiU3VwZXJmaWNpZU1pbmltdW0iOiIiLCJTdXBlcmZpY2llTWF4aW11bSI6IiIsIlVuaXRl"145    "TWVzdXJlIjoiUEMiLCJNb3RzQ2xlcyI6bnVsbCwiWm9uYWdlIjpudWxsLCJOb21icmVVbml0ZXMiOjEs"146    "IlN1Y2N1cnNhbGVDb2RlIjpudWxsLCJBZ2VuY2VDb2RlIjpudWxsLCJNZW1icmVDb2RlIjpudWxsLCJF"147    "cXVpcGVJZCI6MCwiU3VjY3Vyc2FsZU5hbWUiOm51bGwsIkFnZW5jZU5hbWUiOm51bGwsIk1lbWJyZU5h"148    "bWUiOm51bGwsIkVxdWlwZU5hbWUiOm51bGwsImlucHV0UmVnaW9ucyI6bnVsbCwiUmV0dXJuVXJsIjpu"149    "dWxsLCJMYXRpdHVkZSI6bnVsbCwiTG9uZ2l0dWRlIjpudWxsLCJOb0luc2NyaXB0aW9uTm9uRGlzcG8i"150    "Om51bGwsIkVuUmVjaGVyY2hlIjpmYWxzZSwiUGx1c0RlQ3JpdGVyZXMiOiJmYWxzZSIsIlNwZWNpYWxp"151    "dGUiOm51bGwsIk5vbVBsYW5FYXUiOm51bGwsIk5vbVBsYW5FYXVNb2JpbGUiOm51bGwsIklkUGxhbkVh"152    "dSI6bnVsbCwiSWRQbGFuRWF1TW9iaWxlIjowLCJHZW5yZVByb3ByaWV0ZUZyVXJsIjpudWxsLCJHZW5y"153    "ZVByb3ByaWV0ZUVuVXJsIjpudWxsLCJzZWxlY1BBTW9iaWxlIjpudWxsLCJzZWxlY0NhcmFjTW9iaWxl"154    "IjpbbnVsbCxudWxsLG51bGwsbnVsbCxudWxsLG51bGwsbnVsbCxudWxsLG51bGwsbnVsbF0sInNlbGVj"155    "QUNNb2JpbGUiOltudWxsLG51bGwsbnVsbCxudWxsLG51bGwsbnVsbCxudWxsLG51bGwsbnVsbCxudWxs"156    "XSwic2VsZWNUQk1vYmlsZSI6W251bGwsbnVsbCxudWxsLG51bGwsbnVsbCxudWxsLG51bGwsbnVsbCxu"157    "dWxsLG51bGxdfQ=="158)159IMG_HOST = "https://images.viacapitale.info"160161# Un bloc-carte commence à un lien vers une fiche d'inscription horodatée162CARD_SPLIT = re.compile(r'<a href="(https://www\.viacapitalevendu\.com/[^"]*?-(\d{6,}))"')163PRICE_RE = re.compile(r'class="price">\s*([\d   ]+\$)', re.I)164ADDR_RE = re.compile(r'addressListe[^>]*>\s*<a[^>]*title="([^"]+)"', re.I)165IMG_RE = re.compile(r'images\.viacapitale\.info/images/inscriptions/(\d+)/([^"?)\s]+)', re.I)166TYPE_RE = re.compile(167    r'(Maison[\w\s\-àâéèêëîïôûùç]*|Condo[\w\s]*|Duplex|Triplex|Quadruplex|Quintuplex|'168    r'Plex|Terrain|Chalet|Fermette|Ferme|Loft|Terre|Maison de ville|Jumelé)',169    re.I)170171172class ViaCapitaleConnector(BaseConnector):173    source_id = "via_capitale"174175    def fetch(self) -> list[PropertyListing]:176        by_id: dict[str, PropertyListing] = {}177        empty_streak = 0178        last_error = ""179        for page in range(1, MAX_PAGES + 1):180            url = f"{SEARCH}?page={page}&criteresJson={CRITERES_JSON}"181            # Cloudflare renvoie parfois un challenge/vide par intermittence :182            # on retente la page une fois avant de la considérer vraiment vide.183            cards = []184            for attempt in range(2):185                try:186                    # Firecrawl (proxy stealth) : c'est LUI qui rend les cartes de187                    # Via Capitale. Testé : Scrapfly ASP franchit Cloudflare mais188                    # ne déclenche pas le rendu des inscriptions (0 carte) ; on189                    # garde donc Firecrawl, qui ramène bien les ~5 300 propriétés.190                    html = self.get_rendered(url, wait_for=6000, proxy="stealth")191                except Exception as exc:192                    html = ""193                    last_error = f"{exc}"[:300]194                cards = self._parse_cards(html)195                if cards:196                    break197            new = 0198            for lst in cards:199                if lst.uid not in by_id:200                    by_id[lst.uid] = lst201                    new += 1202            if not cards or new == 0:203                empty_streak += 1204                # tolérance élevée : ~155 pages attendues, on ne s'arrête qu'après205                # plusieurs pages consécutives réellement sans nouveauté206                if empty_streak >= 5:207                    break208            else:209                empty_streak = 0210        listings = list(by_id.values())211        if not listings:212            # jamais de zéro silencieux : l'échec est journalisé (ok=0) avec sa213            # cause (clé Firecrawl refusée, quota, challenge) et rien n'est retiré214            raise RuntimeError("Via Capitale : aucune carte extraite — "215                               + (last_error or "pages rendues sans inscription"))216        # fiche détail : galerie + description + specs (chambres, sdb,217        # superficies, année, taxes/évaluation). v3 = extraction des specs.218        du.enrich(self, listings, DETAIL_LIMIT, parse_vc_detail, key="v3",219                  fetch_html=self._fetch_fiche)220        return listings221222    def _fetch_fiche(self, url: str) -> str:223        """HTML de la fiche : requête directe d'abord (passe en général), puis224        repli Firecrawl stealth si Cloudflare renvoie son challenge (403)."""225        try:226            html = self.get(url).text227            if len(html) > 20000:          # une vraie fiche fait ~300 ko228                return html229        except Exception:230            pass231        return self.get_rendered(url, wait_for=4000, proxy="stealth")232233    def _parse_cards(self, html: str) -> list[PropertyListing]:234        # découpe la page en segments, un par carte (lien fiche + id)235        matches = list(CARD_SPLIT.finditer(html))236        out = []237        for i, m in enumerate(matches):238            url, code = m.group(1), m.group(2)239            seg = html[m.start(): matches[i + 1].start() if i + 1 < len(matches) else m.start() + 2500]240            out.append(self._to_listing(url, code, seg))241        return [x for x in out if x]242243    def _to_listing(self, url: str, code: str, seg: str) -> PropertyListing | None:244        price_m = PRICE_RE.search(seg)245        price_label = (price_m.group(1).strip() if price_m else "").replace(" ", " ")246        addr_m = ADDR_RE.search(seg)247        address_full = _unescape(addr_m.group(1).strip()) if addr_m else ""248        type_m = TYPE_RE.search(re.sub(r"<[^>]+>", " ", seg))249        # ne garder que le libellé de type (avant l'adresse recopiée dans le bloc)250        prop_type = re.split(r"\s{2,}|\n", type_m.group(1))[0].strip() if type_m else ""251252        address, city, sector = _split_addr(address_full)253254        images = []255        for im in IMG_RE.finditer(seg):256            u = f"{IMG_HOST}/images/inscriptions/{im.group(1)}/{im.group(2)}"257            if u not in images:258                images.append(u)259260        region, _city_slug = _from_slug(url)261        return PropertyListing(262            source=self.source_id,263            external_id=code,264            url=f"{SITE}/inscription/fichedescriptive/?code={code}",265            title=f"{prop_type} — {address}".strip(" —") or address_full,266            address=address,267            city=city or _city_slug,268            sector=sector,269            region=region,270            property_type=prop_type,271            price=parse_price(price_label),272            price_label=price_label,273            images=images,274            broker_name="Via Capitale",275        )276277278# slug ex. « saguenay-lac-saint-jean-sainte-hedwidge-ch-de-la-lievre-maison-... »279_REGIONS = (280    "bas-saint-laurent", "saguenay-lac-saint-jean", "capitale-nationale",281    "mauricie", "estrie", "montreal", "outaouais", "abitibi-temiscamingue",282    "cote-nord", "nord-du-quebec", "gaspesie-iles-de-la-madeleine",283    "chaudiere-appalaches", "laval", "lanaudiere", "laurentides",284    "monteregie", "centre-du-quebec",285)286287288import html as _htmlmod289290_PAREN = re.compile(r"\(([^)]*)\)")291292293def _unescape(s: str) -> str:294    return _htmlmod.unescape(s).replace("\xa0", " ").replace("&nbsp;", " ").strip()295296297def _split_addr(full: str) -> tuple[str, str, str]:298    """« 1455 Rue des Cèdres, Lévis (Les Chutes-de-la-Chaudière-Ouest) »299    -> (adresse, ville, secteur)."""300    if not full:301        return "", "", ""302    parts = [p.strip() for p in full.split(",", 1)]303    address = parts[0]304    city = sector = ""305    if len(parts) > 1:306        muni = parts[1]307        parens = _PAREN.findall(muni)308        city = _PAREN.sub("", muni).strip()309        if parens:310            sector = parens[-1].strip()311    return address, city, sector312313314def parse_vc_detail(html: str) -> dict:315    """Fiche Via Capitale : galerie complète, description, et specs structurées316    (chambres, salles de bains, superficies, année, taxes, évaluation)."""317    out: dict = {}318    seen, imgs = set(), []319    for m in _FICHE_IMG_RE.finditer(html):320        u = f"https://images.viacapitale.info/images/inscriptions/{m.group(1)}/{m.group(2)}"321        if u not in seen:322            seen.add(u)323            imgs.append(u)324    if imgs:325        out["images"] = imgs326    # description = plus long bloc de texte visible (marketing de la propriété)327    best = ""328    for b in re.findall(r"<div[^>]*>(.*?)</div>", html, re.S):329        txt = re.sub(r"\s+", " ", _htmlmod2.unescape(re.sub(r"<[^>]+>", " ", b))).strip()330        if len(txt) > len(best) and "window" not in txt and "function" not in txt and "{" not in txt:331            best = txt332    if len(best) > 120:333        out["description"] = best[:4000]334335    # chambres / salles de bains / superficie / année : meta description de la336    # fiche (« 2018, 5 chambres, 2 salle(s) de bain, Superficie 2324pi² »)337    meta = re.search(r'<meta name="(?:og:)?description" content="([^"]*)"', html)338    m = _META_SPECS_RE.search(_unescape(meta.group(1))) if meta else None339    if m:340        if m.group(1):341            out["year_built"] = int(m.group(1))342        out["bedrooms"] = int(m.group(2))343        try:344            out["bathrooms"] = int(float(m.group(3).replace(",", ".")))345        except ValueError:346            pass347        if m.group(4):348            try:349                out["area_sqft"] = float(re.sub(r"[^\d]", "", m.group(4)))350            except ValueError:351                pass352353    flat = du.flatten(html)354    details: dict = du.centris_details(flat)355356    # tableau « Libellé | Valeur » : specs numériques prioritaires sur la meta357    m = _VC_YEAR_RE.search(flat)358    if m:359        out["year_built"] = int(m.group(1))360    m = _VC_AREA_RE.search(flat)361    if m:362        v = parse_area_sqft(f"{m.group(1)} {m.group(2)}".replace("pc", "pi²").replace("mc", "m²"))363        if v:364            out["area_sqft"] = v365    m = _VC_LOT_RE.search(flat)366    if m:367        v = parse_area_sqft(f"{m.group(1)} {m.group(2)}".replace("pc", "pi²").replace("mc", "m²"))368        if v:369            out["lot_sqft"] = v370371    # taxes et évaluation municipale (« Taxes et coûts » / « Évaluations (AAAA) »)372    def _amt(g: str) -> str:373        return re.sub(r"[\s  ]+", " ", g).strip()374    m = _VC_TAX_MUNI_RE.search(flat)375    if m:376        details["Taxes municipales"] = _amt(m.group(2)) + \377            (f" ({m.group(1)})" if m.group(1) else "")378    m = _VC_TAX_SCOL_RE.search(flat)379    if m:380        details["Taxes scolaires"] = _amt(m.group(2)) + \381            (f" ({m.group(1)})" if m.group(1) else "")382    m = _VC_EVAL_RE.search(flat)383    if m:384        details["Évaluation municipale (bâtiment)"] = _amt(m.group(2))385        details["Évaluation municipale (terrain)"] = _amt(m.group(3))386        if m.group(1):387            details["Évaluation municipale (année)"] = m.group(1)388389    if details:390        out["details"] = details391    return out392393394def _from_slug(url: str) -> tuple[str, str]:395    tail = url.rstrip("/").rsplit("/", 1)[-1]396    for reg in _REGIONS:397        if tail.startswith(reg):398            rest = tail[len(reg) + 1:]399            city = rest.split("-")[0].replace("-", " ").title() if rest else ""400            return reg.replace("-", " ").title(), city401    return "", ""402
Files main
Menu

Theme