SPB Git

Repository Public

citiluxx.py 10.5 KB 257 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/citiluxx.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-2513# 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# Lou-Ka — Agrégateur de logements à louer (province de Québec)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# connectors/citiluxx.py : connecteur Citiluxx (citiluxx.com — Groupe Cleary)91#   Condos locatifs tout inclus au Faubourg Cousineau, 8121 boulevard92#   Cousineau, Saint-Hubert (Longueuil). WordPress (Astra/Elementor) rendu93#   serveur : la page /plans-appartements-a-louer/ publie le prix plancher94#   par typologie (« 3 1/2 à louer : à partir de 1 932$/mois »…) et embarque95#   le widget Smart Condo Plans (API JSON publique smartcondoplans.silo.immo,96#   projet « citiluxx ») qui fournit le plan des ~199 unités (chambres,97#   salles de bain, superficies) — mais SANS prix ni disponibilité par unité.98#   Granularité : une annonce par typologie (prix « à partir de »), enrichie99#   des superficies min-max et du nombre d'unités via l'API Silo.100#   2026-09-13 : SiteGround sert son anti-bot sgcaptcha (202 + challenge JS,101#   en-tête sg-captcha) aux IP datacenter — invisible du wrapper résilient102#   (2xx) ; on bascule alors la session sur un proxy résidentiel Oxylabs CA103#   (même pattern que boreal_abitibi, hébergeur SiteGround identique).104# -----------------------------------------------------------------------------105from __future__ import annotations106107import os108import re109import time110from urllib.parse import quote111112from ..schema import Listing, normalize_unit_type, parse_price113from .base import BaseConnector114115BASE = "https://citiluxx.com"116PLANS_URL = f"{BASE}/plans-appartements-a-louer/"117SILO_API = ("https://smartcondoplans.silo.immo/v2/building/get-project-data"118            "?project=citiluxx&language=fr")119120ADDRESS = "8121, boulevard Cousineau, Saint-Hubert"121CITY = "Longueuil"122SECTOR = "Saint-Hubert"123124# « 3 1/2 à louer : à partir de 1 932$/mois »125PRICE_RE = re.compile(126    r"(\d)\s*(?:½|1/2)\s*(?:\([^)]*\)\s*)?(?::|à louer\s*:)\s*"127    r"[àa] partir de\s*([\d\s,]{3,9})\s*\$\s*/\s*mois", re.I)128IMG_RE = re.compile(129    r"https://citiluxx\.com/wp-content/uploads/"130    r'[^"\s\\)]+\.(?:jpe?g|png|webp)', re.I)131132# nb de chambres (API Silo, champ `room`) -> typologie québécoise133UT_OF_ROOMS = {1: "3½", 2: "4½", 3: "5½"}134135# page interstitielle sgcaptcha SiteGround (meta refresh vers /.well-known/…)136_SG_MARKER = "/.well-known/sgcaptcha/"137138139def _sg_challenge(resp) -> bool:140    """True si la réponse est le challenge anti-bot SiteGround (202 + JS)."""141    if "challenge" in str(resp.headers.get("sg-captcha", "")).lower():142        return True143    return _SG_MARKER in (resp.text or "")[:600]144145AMENITIES = [146    "Formule tout inclus (chauffage, climatisation, électricité, eau chaude)",147    "5 électroménagers haut de gamme",148    "Concierge",149    "Hauts plafonds de 9 pieds",150    "Comptoirs en quartz",151    "Grand balcon-terrasse",152    "Casiers à colis intelligents",153    "Espace lave-auto",154    "Stationnement intérieur ($) avec espace vélo",155    "Animaux acceptés (max 15 lb, conditions)",156]157158159class CitiluxxConnector(BaseConnector):160    source_id = "citiluxx"161    request_delay = 0.8162163    def _enable_residential_proxy(self) -> bool:164        """Route toute la session via Oxylabs résidentiel CA (session collante)."""165        endpoint = os.environ.get("OXYLABS_PROXY")166        user = os.environ.get("OXYLABS_PROXY_USER")167        pwd = os.environ.get("OXYLABS_PROXY_PASS")168        if not (endpoint and user and pwd):169            return False170        puser = f"{user}-cc-CA-sessid-citiluxx{int(time.time())}-sesstime-10"171        proxy = f"http://{quote(puser, safe='')}:{quote(pwd, safe='')}@{endpoint}"172        self.session.proxies = {"http": proxy, "https": proxy}173        self.session.verify = False  # CA MITM du proxy Oxylabs (cf. _resilient)174        return True175176    def _get_html(self, url: str) -> str:177        """GET avec contournement du challenge sgcaptcha (proxy résidentiel)."""178        resp = self.get(url)179        if not _sg_challenge(resp):180            return resp.text181        if not self.session.proxies and self._enable_residential_proxy():182            resp = self.get(url)183            if not _sg_challenge(resp):184                return resp.text185        raise RuntimeError(f"challenge sgcaptcha non contourné — {url}")186187    def fetch(self) -> list[Listing]:188        listings: list[Listing] = []189        html = self._get_html(PLANS_URL)190        text = re.sub(r"\s+", " ", re.sub(r"<[^>]+>", " ", html))191192        images = [u for u in dict.fromkeys(IMG_RE.findall(html))193                  if not re.search(r"logo|icon|favicon|cropped-|Plans?\.webp|"194                                   r"-\d{2,3}x\d{2,3}\.", u, re.I)][:15]195196        # enrichissement : plan des unités via l'API Silo (superficies,197        # nombre d'unités par typologie) — best effort, jamais bloquant198        silo: dict[str, dict] = {}199        try:200            data = self.get(SILO_API, headers={"Accept": "application/json"}).json()201            for u in data.get("units") or []:202                if u.get("not_unit") or u.get("hide"):203                    continue204                ut = UT_OF_ROOMS.get(u.get("room"))205                if not ut:206                    continue207                s = silo.setdefault(ut, {"n": 0, "areas": [], "baths": set()})208                s["n"] += 1209                if u.get("area"):210                    s["areas"].append(float(u["area"]))211                if u.get("bathroom"):212                    s["baths"].add(u["bathroom"])213        except Exception:214            silo = {}215216        seen: set[str] = set()217        for n, price_txt in PRICE_RE.findall(text):218            ut = normalize_unit_type(f"{n}½")219            if ut in seen:220                continue221            seen.add(ut)222            price_label = f"à partir de {price_txt.strip()}$/mois"223224            desc = ("Condos locatifs neufs tout inclus Citiluxx au Faubourg "225                    "Cousineau (Saint-Hubert, Longueuil) : espaces de vie "226                    "ouverts, abondante luminosité, finitions haut de gamme. "227                    "Phases 1 et 2 en occupation immédiate.")228            details: dict = {}229            area_min = None230            s = silo.get(ut)231            if s and s["areas"]:232                area_min = min(s["areas"])233                desc += (f" Superficies de {int(min(s['areas']))} à "234                         f"{int(max(s['areas']))} pi² selon l'unité "235                         f"({s['n']} unités de ce type au plan).")236                details["building_units"] = s["n"]237238            listings.append(Listing(239                source=self.source_id,240                external_id=f"citiluxx-{n}.5",241                url=PLANS_URL,242                title=f"Citiluxx — {ut} au Faubourg Cousineau",243                address=ADDRESS,244                sector=SECTOR,245                city=CITY,246                unit_type=ut,247                price=parse_price(price_label),248                price_label=price_label,249                availability="Occupation immédiate",250                area_sqft=area_min,251                description=desc,252                amenities=list(AMENITIES),253                details=details,254                images=images,255            ))256        return listings257
Files main
Menu

Theme