Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/royal_laval.py10# Module : louka11# Repository : https://git.spboucher.ai/lou-ka12# Created : 2026-08-2513# Last Modified : 2026-08-2514#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_laval.py : connecteur Gestion Immobilière Royal91# (gestionroyal.com) — gestionnaire de Laval-des-Rapides et Montréal92# (~16 annonces actives). WordPress + thème immobilier Houzez rendu93# serveur : la page /a-louer/ (+ /a-louer/page/N/) affiche des cartes94# .item-listing-wrap complètes (post ID data-hz-id, prix, adresse, type95# n½ en étiquette, galerie data-images). La page détail /property/…96# fournit description et ville (bloc « Ville | … ») via le cache detail().97# Granularité UNITÉ (une annonce par logement).98# -----------------------------------------------------------------------------99from __future__ import annotations100101import json102import re103104from bs4 import BeautifulSoup105106from ..schema import Listing107from .base import BaseConnector108109BASE = "https://gestionroyal.com"110LIST_URL = f"{BASE}/a-louer/"111MAX_PAGES = 10112113HZ_ID_RE = re.compile(r"^hz-(\d+)$")114UNIT_LABEL_RE = re.compile(r"^\s*\d\s*(?:1/2|½)\s*$")115PRICE_RE = re.compile(r"\$?\s*([\d, ]{3,9})\s*\$?(?:\s*/\s*mois)?", re.I)116CITY_RE = re.compile(117 r"\b(Laval|Montréal|Montreal|Saint-Léonard|Longueuil|Terrebonne)\b", re.I)118119120class RoyalLavalConnector(BaseConnector):121 source_id = "royal_laval"122 request_delay = 0.8123124 def fetch(self) -> list[Listing]:125 listings: list[Listing] = []126 seen: set[str] = set()127 url = LIST_URL128 for _ in range(MAX_PAGES):129 try:130 html = self.get(url).text131 except Exception:132 break133 soup = BeautifulSoup(html, "html.parser")134 for card in soup.select(".item-listing-wrap"):135 lst = self._from_card(card)136 if lst is not None and lst.external_id not in seen:137 seen.add(lst.external_id)138 listings.append(lst)139 nxt = soup.select_one('a[href*="/a-louer/page/"]')140 nxt_url = nxt.get("href") if nxt else ""141 if not nxt_url or nxt_url == url:142 break143 url = nxt_url144 return listings145146 def _from_card(self, card) -> Listing | None:147 m = HZ_ID_RE.match(card.get("data-hz-id") or "")148 if not m:149 return None150 post_id = m.group(1) # ID WordPress : stable151152 statuses = {a.get_text(strip=True) for a in card.select(".label-status")}153 if "À Louer" not in statuses:154 return None # vendu/loué155156 link = card.select_one('.item-title a[href*="/property/"]') \157 or card.select_one('a[href*="/property/"]')158 if link is None:159 return None160 url = link.get("href") or LIST_URL161 title = link.get_text(" ", strip=True)162163 addr_el = card.select_one(".item-address")164 address = addr_el.get_text(" ", strip=True) if addr_el else ""165 # adresses Houzez très verbeuses (géocodeur complet) : tronquer aux166 # deux premiers segments (rue + quartier)167 short_addr = ", ".join(p.strip() for p in address.split(",")[:2])168169 unit_type = ""170 for lbl in card.select(".hz-label"):171 t = lbl.get_text(strip=True)172 if UNIT_LABEL_RE.match(t):173 unit_type = t174 break175176 price = None177 price_label = ""178 pr = card.select_one(".item-price")179 if pr is not None:180 price_label = pr.get_text(" ", strip=True)181 pm = PRICE_RE.search(price_label)182 if pm:183 try:184 val = float(pm.group(1).replace(",", "").replace(" ", ""))185 if 300 <= val <= 20000:186 price = val187 except ValueError:188 pass189190 if price is None:191 # certaines cartes n'ont pas d'.item-price : le loyer est alors192 # dans le titre (« Condo à louer, Laval … | 1 975$ »)193 tm = re.search(r"(\d[\d ,]{2,7})\s*\$(?:\s*/?\s*mois)?", title)194 if tm:195 try:196 val = float(re.sub(r"[ , ]", "", tm.group(1)))197 if 300 <= val <= 20000:198 price = val199 price_label = price_label or tm.group(0).strip()200 except ValueError:201 pass202203 beds = None204 bel = card.select_one(".h-beds .hz-figure")205 if bel is not None:206 try:207 beds = float(bel.get_text(strip=True))208 except ValueError:209 pass210 baths = None211 bael = card.select_one(".h-baths .hz-figure")212 if bael is not None:213 try:214 baths = float(bael.get_text(strip=True))215 except ValueError:216 pass217218 images: list[str] = []219 try:220 images = [i["image"] for i in json.loads(card.get("data-images") or "[]")221 if isinstance(i, dict) and i.get("image")][:15]222 except (ValueError, TypeError):223 pass224 if not images:225 img = card.select_one("img")226 if img is not None and (img.get("src") or "").startswith("http"):227 images = [img["src"]]228229 # ville : détectée dans l'adresse/le titre, précisée par la page détail230 city = ""231 cm = CITY_RE.search(f"{address} {title}")232 if cm:233 city = cm.group(1)234235 detail = self.detail(post_id, f"{title}|{price_label}|{address}",236 lambda: self._detail(url))237 description = detail.get("description", "")238 city = detail.get("city") or city239 sector = detail.get("sector", "")240241 return Listing(242 source=self.source_id,243 external_id=post_id,244 url=url,245 title=title or short_addr,246 address=short_addr,247 sector=sector,248 city=city,249 unit_type=unit_type,250 bedrooms=beds,251 bathrooms=baths,252 price=price,253 price_label=price_label,254 description=description,255 images=images,256 )257258 # -- page détail /property/… (description + ville) -------------------------259 def _detail(self, url: str) -> dict:260 payload: dict = {}261 try:262 html = self.get(url).text263 except Exception:264 return payload265 soup = BeautifulSoup(html, "html.parser")266 desc = soup.select_one("#property-description-wrap .block-content-wrap")267 if desc is not None:268 payload["description"] = desc.get_text("\n", strip=True)[:4000]269 # bloc « Address » Houzez : liste Ville / Région / State270 for li in soup.select(".block-content-wrap li, .detail-city"):271 txt = li.get_text(" ", strip=True)272 m = re.match(r"^Ville\s+(.+)$", txt)273 if m:274 payload["city"] = m.group(1).strip()275 m = re.match(r"^(?:Quartier|Secteur)\s+(.+)$", txt)276 if m:277 payload["sector"] = m.group(1).strip()278 return payload279