SPB Git

Repository Public

brio.py 11.5 KB 269 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/brio.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-0613# Last Modified    : 2026-09-0814#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/brio.py : connecteur Les Immeubles Brio (immeublesbrio.com)91#   Projet mono-immeuble « Le Brio » à Val-Bélair (boul. Pie-XI, Québec).92#   Les unités sont affichées par étage (hotspots Divi) avec statut93#   Disponible / Loué ; les prix « à partir de » par type (3½/4½/5½)94#   sont affichés sur la page d'accueil.95# -----------------------------------------------------------------------------96from __future__ import annotations9798import re99import time100101from bs4 import BeautifulSoup102103from ..schema import Listing, infer_city, normalize_unit_type, parse_price104from .base import BaseConnector105106BASE = "https://immeublesbrio.com"107HOME_URL = f"{BASE}/"108LIST_URL = f"{BASE}/appartements-a-louer-val-belair/"109SECTOR = "Val-Bélair"110# Adresse civique affichée sur la page Contactez-nous (« Visitez-nous »)111ADDRESS = "1105, rue des Rigoles, Québec, QC G3K 0M7"112113114class BrioConnector(BaseConnector):115    source_id = "brio"116    request_delay = 0.6117118    def _html(self, url: str, marker: str) -> str:119        """HTML de `url`, tolérant au cache CDN empoisonné et au pare-feu Sucuri.120121        Vu 2026-09-07 : le cache Cloudflare du site servait une variante122        brotli figée (content-encoding: br, cf-cache-status HIT) illisible123        par requests — contournée par un paramètre cache-buster.124        Vu 2026-09-08 : le site est passé derrière Sucuri CloudProxy, qui125        répond 307 avec un challenge JavaScript (cookie sucuri_cloudproxy)126        à TOUT client sans navigateur — le wrapper résilient de base.py ne127        le voit pas (307 hors BLOCK_STATUS). On escalade alors vers128        Scrapfly (ASP + rendu JS), qui passe le challenge ; s'il ne livre129        pas non plus le marqueur, échec franc.130        """131        for params in (None, {"lkb": int(time.time())}):132            try:133                html = self.get(url, params=params).text134            except Exception:  # noqa: BLE001 — direct bloqué : on escaladera135                continue136            if marker in html:137                return html138        html = self.get_rendered(url)139        if marker not in html:140            raise RuntimeError(141                f"brio : contenu inattendu (marqueur {marker!r} absent, "142                f"même via Scrapfly — challenge Sucuri non passé ?) — {url}")143        return html144145    def fetch(self) -> list[Listing]:146        # 1) Page d'accueil : prix « à partir de » par type (ex. « 3½ à147        #    partir de 1500$ »), services de l'immeuble (blurbs Divi) et148        #    contact (téléphone/courriel de l'en-tête).149        type_prices: dict[str, tuple[float | None, str]] = {}150        services: list[str] = []151        contact: dict = {}152        try:153            home = self._html(HOME_URL, "partir de")154            home_txt = re.sub(r"<[^>]+>", " ", home)155            for m in re.finditer(r"(\d)\s*½\s*à\s*partir\s*de\s*([\d\s  ]+)\$",156                                 home_txt):157                label = f"{m.group(1)}½ à partir de {m.group(2).strip()}$"158                type_prices[m.group(1)] = (parse_price(f"{m.group(2)}$"), label)159            hsoup = BeautifulSoup(home, "html.parser")160            # Services de l'immeuble (Wifi, ascenseur, stationnement…)161            services = [h.get_text(" ", strip=True)162                        for h in hsoup.select(".et_pb_blurb .et_pb_module_header")163                        if h.get_text(strip=True)][:12]164            # Contact : courriel (lien mailto:) + téléphone (en-tête)165            mail = hsoup.select_one('a[href^="mailto:"]')166            if mail:167                contact["email"] = mail["href"].removeprefix("mailto:").strip()168            m = re.search(r"\b(\d{3})[-.\s](\d{3})[-.\s](\d{4})\b", home_txt)169            if m:170                contact["phone"] = f"{m.group(1)}-{m.group(2)}-{m.group(3)}"171        except Exception:172            pass173174        # 2) Page des appartements : hotspots par étage175        html = self._html(LIST_URL, "hotspot-info")176        soup = BeautifulSoup(html, "html.parser")177178        infos = soup.select("div.hotspot-info")179        if not infos:180            # une page complète contient toujours les hotspots (Disponible181            # ET Loué) — leur absence = rendu partiel, pas un inventaire vide182            raise RuntimeError("brio : aucun hotspot-info dans la page des "183                               "appartements (rendu partiel ?)")184185        # Galerie générale de l'immeuble (photos des pièces)186        gallery = []187        for img in soup.select("img"):188            src = img.get("data-src") or img.get("src") or ""189            if re.search(r"/wp-content/uploads/.*(chambre|salle|salon|cuisine)"190                         r"[^\"]*\.(?:jpg|jpeg|png|webp)$", src, re.I):191                gallery.append(src if src.startswith("http") else BASE + src)192        gallery = list(dict.fromkeys(gallery))[:8]193194        listings: list[Listing] = []195        for info in infos:196            try:197                title_el = info.select_one(".hotspot-title")198                if not title_el:199                    continue200                title = title_el.get_text(" ", strip=True)201                m = re.match(r"(Disponible|Lou[ée])\s*-?\s*Appartement\s*(\d+)"202                             r"\s*:\s*(.+)", title, re.I)203                if not m:204                    continue205                status, num, raw_type = m.groups()206                if not status.lower().startswith("dispo"):207                    continue          # on ne garde que les unités disponibles208209                unit_type = normalize_unit_type(raw_type)210                digit = re.search(r"(\d)", unit_type or "")211                price, price_label = (None, "")212                if digit and digit.group(1) in type_prices:213                    price, price_label = type_prices[digit.group(1)]214215                # Contenu : superficie + caractéristiques216                content = info.select_one(".hotspot-content")217                amenities: list[str] = []218                description = ""219                if content:220                    sup = content.find("strong")221                    if sup:222                        description = sup.get_text(strip=True)223                    amenities = [li.get_text(" ", strip=True)224                                 for li in content.select("li")]225226                # Images : plan de l'unité (vignette + plan complet) + galerie227                images: list[str] = []228                thumb = info.select_one(".hotspot-thumb img")229                if thumb:230                    src = thumb.get("data-src") or thumb.get("src") or ""231                    if src.startswith("http"):232                        # version pleine grandeur (retirer le suffixe -300x284)233                        full = re.sub(r"-\d+x\d+(\.(?:jpg|jpeg|png|webp))$",234                                      r"\1", src)235                        images.append(full)236                if content:237                    for a in content.select("a[href]"):238                        href = a.get("href", "")239                        if re.search(r"\.(?:jpg|jpeg|png|webp)$", href, re.I):240                            images.append(href)241                images.extend(gallery)242                images = list(dict.fromkeys(images))243244                details: dict = {}245                if contact:246                    details["contact"] = dict(contact)247248                listings.append(Listing(249                    source=self.source_id,250                    external_id=f"appartement-{num}",251                    url=LIST_URL,252                    title=f"Le Brio — Appartement {num} ({unit_type})",253                    address=ADDRESS,254                    sector=SECTOR,255                    city=infer_city(SECTOR),256                    unit_type=unit_type,257                    price=price,258                    price_label=price_label,259                    availability="Disponible",260                    description=description,261                    amenities=amenities + services,262                    details=details,263                    images=images,264                ))265            except Exception:266                continue267268        return listings269
Files main
Menu

Theme