Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/cara.py10# Module : louka11# Repository : https://git.spboucher.ai/lou-ka12# Created : 2026-08-2513# Last Modified : 2026-08-2914#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/cara.py : connecteur CARA — condos locatifs à Vaudreuil-Dorion91# (condoscara.com — 1400, rue Émile-Bouchard). ⚠️ Compagnie distincte du92# connecteur `carat_immobilier` (Carat gestion immobilière).93# WordPress + Elementor, mais la grille des disponibilités est une app94# externe Livya (plan interactif « Plan A » — app.livya.com), injectée en95# iframe par le script realvuu : la page /disponibilites/ (rendue serveur)96# porte un div .livya-module-container-plans avec data-entity (UUID du97# plan) et data-project. On reconstruit l'URL de l'app Livya, on la rend98# via Scrapfly (Next.js, unités chargées côté client) puis on lit les99# cartes d'unités : « #116 | Disponible | 1 810 $ | /mois | 3½ | ch | sdb100# | pi² ». Seules les unités au statut « Disponible » sont ingérées101# (les « Loué »/« Réservé » sont exclues).102# -----------------------------------------------------------------------------103from __future__ import annotations104105import re106import time107108from bs4 import BeautifulSoup109110from ..schema import Listing, normalize_unit_type111from .base import BaseConnector112113BASE = "https://www.condoscara.com"114LIST_URL = f"{BASE}/disponibilites/"115LIVYA_FMT = ("https://app.livya.com/fr/plan-a/projects/{project}"116 "/plans/{entity}?noLayout=1")117# plan observé le 2026-08-25 (repli si le data-entity disparaît de la page)118FALLBACK_ENTITY = "6f0dcc75-0b82-4e00-ad67-0f6472ed0a94"119120ADDRESS = "1400, rue Émile-Bouchard, Vaudreuil-Dorion"121CITY = "Vaudreuil-Dorion"122123UNIT_RE = re.compile(r"^#(\d{2,4})$")124PRICE_RE = re.compile(r"^([\d\s ]{3,9})\$$")125TYPE_RE = re.compile(r"^\d½$")126127128class CaraConnector(BaseConnector):129 source_id = "cara"130 request_delay = 0.8131132 def fetch(self) -> list[Listing]:133 listings: list[Listing] = []134135 # 1) page WordPress : UUID du plan Livya (data-entity)136 project, entity = "cara", FALLBACK_ENTITY137 try:138 wp = self.get(LIST_URL).text139 m = re.search(r'class="livya-module-container-plans"[^>]*'140 r'data-project="([^"]+)"[^>]*data-entity="([^"]+)"',141 wp)142 if m:143 project, entity = m.group(1), m.group(2)144 except Exception:145 pass146147 # 2) app Livya rendue (Next.js : unités chargées côté client). Un raté148 # transitoire Scrapfly (contenu vide ou rendu partiel sans cartes,149 # vu 2026-08-29) renvoyait 0 annonce « ok » : retry court, puis150 # erreur franche plutôt qu'un faux zéro.151 url = LIVYA_FMT.format(project=project, entity=entity)152 soup = None153 for attempt in range(3):154 html = self.get_scrapfly(url, render_js=True, asp=True,155 rendering_wait=6000)156 if html:157 soup = BeautifulSoup(html, "html.parser")158 if soup.select("div.Card"):159 break160 if attempt < 2:161 time.sleep(5 * (attempt + 1))162 else:163 raise RuntimeError(164 "rendu Livya sans cartes d'unités après 3 essais Scrapfly")165166 # 3) cartes d'unités : div.Card -> « #116 Disponible 1 810 $ /mois167 # 3½ <ch> <sdb> <pi²> »168 seen: set[str] = set()169 for card in soup.select("div.Card"):170 try:171 bits = [t for t in172 (el.strip() for el in card.stripped_strings) if t]173 if not bits:174 continue175 m = UNIT_RE.match(bits[0])176 if not m:177 continue178 unit_no = m.group(1)179 if unit_no in seen:180 continue181182 status = bits[1] if len(bits) > 1 else ""183 if not re.match(r"Disponible", status, re.I):184 continue # Loué / Réservé / Vendu : exclu185 seen.add(unit_no)186187 price = None188 price_label = ""189 unit_type = ""190 area = None191 counts: list[float] = []192 for i, b in enumerate(bits[2:]):193 b_clean = b.replace(" ", " ").replace(" ", " ")194 mm = PRICE_RE.match(b_clean.replace(" ", ""))195 if mm and price is None:196 try:197 price = float(mm.group(1).replace(" ", ""))198 except ValueError:199 price = None200 nxt = bits[2 + i + 1] if 2 + i + 1 < len(bits) else ""201 price_label = f"{b_clean} {nxt}".strip() \202 if "/mois" in nxt else b_clean203 continue204 if TYPE_RE.match(b_clean) and not unit_type:205 unit_type = normalize_unit_type(b_clean)206 continue207 if b_clean.endswith("pi²") and area is None:208 try:209 area = float(re.sub(r"[^\d]", "",210 b_clean[:-3]))211 except ValueError:212 area = None213 continue214 if re.fullmatch(r"\d", b_clean) and len(counts) < 2:215 counts.append(float(b_clean))216217 bedrooms = counts[0] if counts else None218 bathrooms = counts[1] if len(counts) > 1 else None219220 images: list[str] = []221 for im in card.find_all("img"):222 src = im.get("src") or ""223 # dérouler le proxy Next.js (/_next/image?url=…)224 mm = re.search(r"[?&]url=([^&]+)", src)225 if mm:226 from urllib.parse import unquote227 src = unquote(mm.group(1))228 if src.startswith("http") and src not in images:229 images.append(src)230231 amenities = []232 if bathrooms:233 amenities.append(f"{int(bathrooms)} salle(s) de bain")234235 listings.append(Listing(236 source=self.source_id,237 external_id=unit_no,238 url=LIST_URL,239 title=f"Condo #{unit_no} — CARA",240 address=ADDRESS,241 city=CITY,242 unit_type=unit_type,243 bedrooms=bedrooms,244 bathrooms=bathrooms,245 price=price,246 price_label=price_label,247 availability=status,248 area_sqft=area,249 amenities=amenities,250 images=images[:10],251 ))252 except Exception:253 continue254 return listings255