Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/royal_lepage.py10# Module : louka11# Repository : https://git.spboucher.ai/lou-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# Lou-Ka — Agrégateur de logements à louer (province de Québec)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# connectors/royal_lepage.py : Royal LePage (royallepage.ca) — LOCATIONS Québec91#92# Le portail rend ses résultats côté serveur. La recherche par ville est93# filtrable : /fr/search/homes/{page}/?search_str=...&prov_code=QC&city_name=94# ...&lat=..&lng=..&search_type=city + « transactionType=LEASE » (trouvé dans95# le formulaire caché du site) renvoie les propriétés À LOUER (46/page,96# prix « 1 850.00 $ /mois » sur la carte). Chaque recherche plafonne à97# ~1 250 résultats ; on SHARD par points d'ancrage répartis dans la province98# et on dédoublonne par numéro MLS (dans l'URL /.../mls{no}/). Aucune99# dépendance Firecrawl : requêtes directes. Adapté du connecteur « à vendre »100# d'Immo-Ka (agent-courtage/immoka).101# La fiche détail (accessible en direct, ~0,7 s) fournit ce que la carte102# liste n'a pas : galerie COMPLÈTE (originaux pleine résolution du CDN103# jumplisting, ordre du carrousel), description (« Remarques »), superficie104# habitable, caractéristiques (label/valeur) et bureau — enrichissement105# plafonné (DETAIL_LIMIT/cycle) + cache BD, le parc se complète au fil des106# synchronisations.107# -----------------------------------------------------------------------------108from __future__ import annotations109110import html as _html111import os112import re113114from .base import BaseConnector115from . import _detailutil as du116from ..schema import Listing, parse_area_sqft117118BASE = "https://www.royallepage.ca/fr/search/homes"119MAX_PAGES = 30 # une recherche plafonne à ~27 pages (~1250)120# Description, superficie habitable et bureau (« Royal LePage Humania »…) ne121# sont pas sur la carte : ils viennent de la fiche détail. Enrichissement122# plafonné + cache (se remplit au fil des cycles).123DETAIL_LIMIT = int(os.environ.get("LOUKA_RLP_DETAIL_LIMIT", "100"))124_OFFICE_RE = re.compile(r'agent-info__brokerage".*?<a[^>]*>\s*([^<,\n]+?)\s*(?:,|\n|</a>)',125 re.S | re.I)126# bloc « Remarques » de la fiche : paragraphes de description (+ inclusions/127# exclusions) jusqu'à la section suivante128_DESC_BLOCK_RE = re.compile(r"<h2>\s*Remarques\s*:?\s*</h2>(.*?)(?=<h[24]|"129 r'<div class="details-row"|$)', re.S | re.I)130_DESC_P_RE = re.compile(r'<p class="body-15[^"]*">(.*?)</p>', re.S | re.I)131# « Superficie habitable (approx): » -> « 527 Pieds carrés » (label/value)132_AREA_VAL_RE = re.compile(r'Superficie habitable[^<]*:\s*</span>\s*'133 r'<span class="value">\s*([^<]+)', re.I)134# galerie de la fiche : toutes les photos du carrousel/vignettes, indexées135# « …/photos/28/66/94/65/28669465_3_lg.jpg » ; la variante SANS suffixe136# (28669465_3.jpg) est l'original pleine résolution servi par le CDN.137_GALLERY_RE = re.compile(138 r'//rlp\.jumplisting\.com/photos/(\d+/\d+/\d+/\d+)/(\d+)_(\d+)(?:_[a-z]+)?\.jpe?g',139 re.I)140# tableaux « details-row » de la fiche : paires <span class=label/value>141_LABELVAL_RE = re.compile(r'class="label">\s*([^<]{1,60}?)\s*</span>\s*'142 r'<span class="value">\s*([^<]{1,90}?)\s*<', re.S)143144# Points d'ancrage couvrant le Québec (nom, lat, lng). L'union des recherches145# + dédoublonnage MLS couvre la province.146ANCHORS = [147 ("Montréal", 45.5089, -73.5542), ("Québec", 46.8139, -71.2080),148 ("Gatineau", 45.4765, -75.7013), ("Sherbrooke", 45.4040, -71.8929),149 ("Trois-Rivières", 46.3432, -72.5432), ("Saguenay", 48.4280, -71.0680),150 ("Laval", 45.6066, -73.7124), ("Longueuil", 45.5312, -73.5185),151 ("Drummondville", 45.8833, -72.4833), ("Saint-Jérôme", 45.7803, -74.0038),152 ("Granby", 45.4001, -72.7300), ("Rimouski", 48.4489, -68.5236),153 ("Rouyn-Noranda", 48.2360, -79.0230), ("Val-d'Or", 48.0975, -77.7972),154 ("Gaspé", 48.8330, -64.4870), ("Sept-Îles", 50.2001, -66.3821),155 ("Baie-Comeau", 49.2166, -68.1487), ("Joliette", 46.0167, -73.4500),156 ("Saint-Hyacinthe", 45.6300, -72.9569), ("Sorel-Tracy", 46.0500, -73.1200),157 ("Victoriaville", 46.0533, -71.9667), ("Mont-Laurier", 46.5500, -75.5000),158 ("Alma", 48.5500, -71.6500), ("Matane", 48.8500, -67.5300),159 ("Saint-Sauveur", 45.8939, -74.2051), ("Baie-Saint-Paul", 47.4400, -70.5000),160 ("Salaberry-de-Valleyfield", 45.2500, -74.1300), ("Thetford Mines", 46.1000, -71.3000),161]162163_CARD_RE = re.compile(r'card--listing-card js-listing js-property-details(.*?)'164 r'(?=card--listing-card js-listing js-property-details|</main>|$)', re.S)165_URL_RE = re.compile(r'/fr/property/quebec/[^"\']+?/mls[a-z0-9]+/', re.I)166_MLS_RE = re.compile(r'/mls([a-z0-9]+)/', re.I)167_KEY_RE = re.compile(r'data-rlp-key="(-?\d+\.\d+)\.(-?\d+\.\d+)"')168_PHOTO_RE = re.compile(r'(//rlp\.jumplisting\.com/photos/[^"\']+)')169_CAC_RE = re.compile(r'(\d+)\s*CAC', re.I)170_SDB_RE = re.compile(r'(\d+)(?:\+\d+)?\s*SDB', re.I)171# loyer sur la carte, aplatie en « 1 850.00 | $ | /mois » (une carte peut aussi172# afficher un prix de VENTE : on ne retient que le montant suivi de /mois)173_RENT_RE = re.compile(r'(\d[\d\s ,.]*?)\s*\|?\s*\$\s*\|?\s*/\s*mois', re.I)174_TYPE_RE = re.compile(r'\|\s*(Maison|Condo|Copropriété|Appartement|Duplex|Triplex|'175 r'Plex|Chalet|Loft|Studio|Maison de ville|Jumelé)\s*\|', re.I)176177178def _parse_rent(raw: str) -> float | None:179 """« 1 850.00 » / « 1,850 » -> 1850.0 ($/mois)."""180 s = raw.replace(" ", "").replace("\xa0", "").replace(" ", "")181 if re.search(r",\d{3}\b", s):182 s = s.replace(",", "")183 else:184 s = s.replace(",", ".")185 try:186 v = float(s)187 except ValueError:188 return None189 return v if 100 <= v <= 50000 else None190191192class RoyalLepageConnector(BaseConnector):193 source_id = "royal_lepage"194 request_delay = 0.4195196 def fetch(self) -> list[Listing]:197 by_id: dict[str, Listing] = {}198 for name, lat, lng in ANCHORS:199 self._search_anchor(name, lat, lng, by_id)200 listings = list(by_id.values())201 # description + galerie complète + superficie + bureau via la fiche202 # détail — plafonné, cache accumulé (clé « detail3 » : remplace203 # detail2, qui ne captait pas la galerie ni les caractéristiques)204 du.enrich(self, listings, DETAIL_LIMIT, _parse_rlp_detail, key="detail3")205 return listings206207 def _search_anchor(self, name: str, lat: float, lng: float, out: dict) -> None:208 empty_streak = 0209 for page in range(1, MAX_PAGES + 1):210 params = {211 "search_str": f"{name}, QC", "prov_code": "QC",212 "city_name": name, "lat": lat, "lng": lng, "search_type": "city",213 "transactionType": "LEASE",214 }215 try:216 html = self.get(f"{BASE}/{page}/", params=params,217 headers={"X-Requested-With": "XMLHttpRequest"}).text218 except Exception:219 break220 new = 0221 for lst in self._parse_cards(html):222 if lst.external_id not in out:223 out[lst.external_id] = lst224 new += 1225 if new == 0:226 empty_streak += 1227 if empty_streak >= 2: # cap serveur atteint (page répétée)228 break229 else:230 empty_streak = 0231232 def _parse_cards(self, html: str) -> list[Listing]:233 out = []234 for seg in _CARD_RE.findall(html):235 murl = _URL_RE.search(seg)236 if not murl:237 continue238 url = "https://www.royallepage.ca" + murl.group(0)239 mls = _MLS_RE.search(url)240 ext = mls.group(1) if mls else url241 # /fr/property/quebec/{ville}/{adresse}/{id}/mls{no}/242 parts = murl.group(0).strip("/").split("/")243 city = parts[3].replace("-", " ").title() if len(parts) > 3 else ""244 address = parts[4].replace("-", " ").title() if len(parts) > 4 else ""245 sector = ""246 # « Montreal Ville Marie » → ville + arrondissement247 for big, accent in (("Montreal", "Montréal"), ("Quebec", "Québec"),248 ("Levis", "Lévis"), ("Gatineau", "Gatineau"),249 ("Longueuil", "Longueuil"), ("Laval", "Laval")):250 if city == big:251 city = accent252 break253 if city.startswith(big + " "):254 sector = city[len(big) + 1:]255 city = accent256 break257 flat = _html.unescape(re.sub(r"<[^>]+>", " | ", seg))258 flat = re.sub(r"(\s*\|\s*)+", " | ", re.sub(r"\s+", " ", flat))259 rent = _RENT_RE.search(flat)260 price = _parse_rent(rent.group(1)) if rent else None261 if price is None:262 continue # pas de « $ /mois » = pas une location263 beds = _CAC_RE.search(flat)264 baths = _SDB_RE.search(flat)265 typ = _TYPE_RE.search(flat)266 key = _KEY_RE.search(seg)267 photo = _PHOTO_RE.search(seg)268 images = []269 if photo:270 images = ["https:" + photo.group(1).replace("_0_med", "_0_lg")]271 unit_type = ""272 if typ and typ.group(1).lower() in ("loft", "studio"):273 unit_type = typ.group(1).title()274 elif beds:275 unit_type = f"{beds.group(1)} chambres" # normalisé en n+2 ½276 details = {"Courtier": "Royal LePage"}277 if mls:278 details["MLS"] = mls.group(1)279 if typ:280 details["Type"] = typ.group(1)281 if baths:282 details["Salles de bain"] = baths.group(1)283 out.append(Listing(284 source=self.source_id, external_id=str(ext), url=url,285 title=address, address=address, city=city, sector=sector,286 unit_type=unit_type,287 price=price,288 price_label=f"{price:,.0f} $/mois".replace(",", " "),289 details=details,290 images=images,291 lat=float(key.group(1)) if key else None,292 lng=float(key.group(2)) if key else None,293 ))294 return out295296297def _parse_rlp_office(html: str) -> dict:298 """Extrait le bureau/brokerage (sous-agence) de la fiche détail."""299 m = _OFFICE_RE.search(html)300 if not m:301 return {}302 office = _html.unescape(m.group(1)).strip()303 return {"details": {"Agence": office}} if office else {}304305306def _parse_rlp_detail(html: str) -> dict:307 """Fiche détail complète : bureau + description (« Remarques », avec les308 paragraphes Inclusions/Exclusions — extract_details les minera) +309 galerie complète (originaux pleine résolution, ordre du carrousel) +310 superficie habitable + caractéristiques (tableaux label/valeur)."""311 out = _parse_rlp_office(html)312313 # galerie : toutes les photos de l'annonce (les portraits d'agents sont314 # sous /photos/agents/ et ne matchent pas le motif dossier numérique) ;315 # ordre = index du carrousel, URL sans suffixe = original pleine résolution316 photos: dict[int, str] = {}317 for path, pid, idx in _GALLERY_RE.findall(html):318 photos.setdefault(319 int(idx), f"https://rlp.jumplisting.com/photos/{path}/{pid}_{idx}.jpg")320 if photos:321 out["images"] = [photos[i] for i in sorted(photos)]322323 # caractéristiques structurées (Bâti en, Stationnement, Chauffage…)324 details = out.get("details") or {}325 for label, value in _LABELVAL_RE.findall(html):326 label = _html.unescape(label).strip().rstrip(" :*")327 value = _html.unescape(re.sub(r"\s+", " ", value)).strip().rstrip(",")328 if (not label or not value or "." in label # clés techniques329 or label.lower() in ("description",)):330 continue331 details.setdefault(label, value)332 if details:333 out["details"] = details334335 tour = du.virtual_tour(html)336 if tour:337 out["virtual_tour"] = tour # apply_detail -> details.virtual_tour338339 m = _DESC_BLOCK_RE.search(html)340 if m:341 paras = []342 for p in _DESC_P_RE.findall(m.group(1)):343 t = _html.unescape(re.sub(r"<br\s*/?>", "\n", p))344 t = re.sub(r"<[^>]+>", " ", t)345 t = re.sub(r"[ \t]+", " ", t).strip()346 if t:347 paras.append(t)348 if paras:349 out["description"] = "\n\n".join(paras)[:6000]350 m = _AREA_VAL_RE.search(html)351 if m:352 area = parse_area_sqft(m.group(1))353 if area:354 out["area_sqft"] = area355 return out356