Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/plan_a.py10# Module : louka11# Repository : https://git.spboucher.ai/lou-ka12# Created : 2026-08-0613# Last Modified : 2026-08-0914#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/plan_a.py : connecteur Plan A Immobilier (plan-a.ca)91# ~3500 unités dans des complexes locatifs (Pierrefonds-Roxboro,92# Pointe-aux-Trembles, Ahuntsic, Laval, Vaudreuil-Dorion, Sherbrooke —93# les projets de Saguenay sont encore exclus). WordPress rendu serveur :94# la page « appartements et condos à louer » expose des cartes-projets95# a.c-card[data-listing=project] avec un JSON data-filters-item (ville,96# budget min, types), le carrousel d'images et le prix « à partir de ».97# Granularité = 1 annonce par complexe (prix plancher), fiches /project/98# pour la description et la disponibilité.99# -----------------------------------------------------------------------------100from __future__ import annotations101102import hashlib103import json104import re105106from bs4 import BeautifulSoup107108from ..schema import Listing, parse_price109from .base import BaseConnector110111BASE = "https://plan-a.ca"112LIST_URL = f"{BASE}/plan-a-appartements-et-condos-a-louer/"113114# Villes couvertes (valeurs du champ "city" des cartes) : Grand Montréal115# + Sherbrooke (expansion provinciale 2026-08). Saguenay reste exclu116# (District Jonquière : prévu au lot Est & Nord).117ALLOWED_CITIES = {118 "montreal": "Montréal",119 "laval": "Laval",120 "vaudreuil-dorion": "Vaudreuil-Dorion", # Montérégie ouest / CMM121 "longueuil": "Longueuil",122 "sherbrooke": "Sherbrooke",123}124125# Secteur (quartier) déduit du slug pour les projets montréalais126_SECTOR_HINTS = [127 ("pierrefonds", "Pierrefonds-Roxboro"),128 ("roxboro", "Pierrefonds-Roxboro"),129 ("gouin", "Pierrefonds-Roxboro"),130 ("pointe-aux-trembles", "Pointe-aux-Trembles"),131 ("ahuntsic", "Ahuntsic"),132 ("cremazie", "Ahuntsic"),133 ("community-high-school", "Pierrefonds-Roxboro"),134]135136137class PlanAConnector(BaseConnector):138 source_id = "plan_a"139 request_delay = 0.6140 max_details = 20 # garde-fou de fetch des fiches projets141142 def fetch(self) -> list[Listing]:143 listings: list[Listing] = []144 try:145 html = self.get(LIST_URL).text146 except Exception:147 return listings148 soup = BeautifulSoup(html, "html.parser")149150 for card in soup.select('a.c-card[data-listing="project"]'):151 try:152 lst = self._parse_card(card)153 except Exception:154 continue155 if lst:156 listings.append(lst)157158 # Fiches projets (via cache self.detail : une vraie requête seulement159 # si la carte liste a changé) : description, disponibilité, quartier,160 # commodités des unités, services de l'immeuble, types, galerie.161 budget = {"n": 0}162 for lst in listings:163 key = hashlib.sha1("|".join(164 (lst.price_label, lst.availability, lst.unit_type,165 lst.address)).encode()).hexdigest()166167 def _fetch(url=lst.url):168 if budget["n"] >= self.max_details:169 raise RuntimeError("plafond de fiches atteint")170 budget["n"] += 1171 return self._parse_detail(self.get(url).text)172173 try:174 payload = self.detail(lst.external_id, key, _fetch)175 except Exception:176 continue177 if payload.get("description"):178 lst.description = payload["description"]179 if payload.get("availability"):180 lst.availability = payload["availability"]181 if payload.get("unit_type"):182 lst.unit_type = payload["unit_type"]183 if payload.get("amenities"):184 lst.amenities = payload["amenities"]185 if payload.get("images"):186 imgs = lst.images + [u for u in payload["images"]187 if u not in lst.images]188 lst.images = imgs[:20]189 if not lst.sector and lst.city == "Montréal" and payload.get("sector"):190 lst.sector = payload["sector"]191192 return listings193194 # -- fiche /project/<slug>/ ------------------------------------------------195 @staticmethod196 def _parse_detail(detail: str) -> dict:197 payload: dict = {}198 dsoup = BeautifulSoup(detail, "html.parser")199200 og = dsoup.find("meta", attrs={"property": "og:description"}) or \201 dsoup.find("meta", attrs={"name": "description"})202 if og and og.get("content"):203 payload["description"] = og["content"].strip()[:600]204205 text = re.sub(r"\s+", " ", dsoup.get_text(" ", strip=True))206 m = re.search(r"Prochaine disponibilité\s+(.{3,40}?)\s+Unités", text)207 availability = m.group(1).strip() if m else ""208 m = re.search(r"Unités? disponibles?\s+(\d+\s*/\s*\d+)", text)209 if m:210 availability = f"{availability} ({m.group(1)} unités)".strip()211 if availability:212 payload["availability"] = availability[:120]213214 m = re.search(r"QUARTIER\s+([A-ZÀ-Ü][\w\-]+(?:[ \-][A-ZÀ-Ü][\w\-]+)*)",215 text)216 if m:217 payload["sector"] = m.group(1).strip()218219 # Types d'unités disponibles (entête de fiche, plus complet que la carte)220 types = [re.sub(r"\s+", "", el.get_text(strip=True))221 for el in dsoup.select(".c-info_unit")]222 types = [t for t in dict.fromkeys(types)223 if re.fullmatch(r"\d½|Studio|Loft", t)]224 if types:225 payload["unit_type"] = ", ".join(types)226227 # Commodités des unités (section .c-feature) + services de l'immeuble228 # (liste à puces sous « SERVICES DANS L'IMMEUBLE ») + atouts (carrousel)229 amenities: list[str] = []230 for sec in dsoup.select("section"):231 over = sec.select_one(".c-overline")232 if over and "commodit" in over.get_text(strip=True).lower():233 for p in sec.select(".c-feature p"):234 t = re.sub(r"\s+", " ", p.get_text(" ", strip=True))235 if t and t not in amenities:236 amenities.append(t)237 for h4 in dsoup.find_all("h4"):238 if "services dans l" in h4.get_text(strip=True).lower():239 ul = h4.find_next("ul")240 if ul:241 for li in ul.find_all("li"):242 t = li.get_text(" ", strip=True).lstrip("• ").strip()243 if t and t not in amenities:244 amenities.append(t)245 break246 for h4 in dsoup.select(".c-cell_title h4"):247 t = re.sub(r"\s+", " ", h4.get_text(" ", strip=True))248 if t and t not in amenities:249 amenities.append(t)250 if amenities:251 payload["amenities"] = amenities[:30]252253 # Galerie : photos wp-content (jamais les icônes svg)254 imgs = []255 for img in dsoup.find_all("img", src=True):256 u = img["src"]257 if re.search(r"/wp-content/uploads/.*\.(?:jpe?g|png|webp)$", u, re.I) \258 and u not in imgs:259 imgs.append(u)260 if imgs:261 payload["images"] = imgs[:20]262263 return payload264265 # -- parsing d'une carte-projet ---------------------------------------------266 def _parse_card(self, card) -> Listing | None:267 href = (card.get("href") or "").split("?")[0]268 m = re.search(r"/project/([a-z0-9\-]+)/?$", href)269 if not m:270 return None271 slug = m.group(1)272273 try:274 filters = json.loads(card.get("data-filters-item") or "{}")275 except (ValueError, TypeError):276 filters = {}277 city_key = (filters.get("city") or "").strip().lower()278 if city_key not in ALLOWED_CITIES:279 return None # Saguenay... exclus280 city = ALLOWED_CITIES[city_key]281282 name_el = card.select_one("h6")283 name = name_el.get_text(" ", strip=True) if name_el else slug284 overline = card.select_one(".c-card_overline")285 locality = overline.get_text(" ", strip=True) if overline else ""286287 subtitles = [s.get_text(" ", strip=True)288 for s in card.select(".c-card_subtitle")]289 address = subtitles[0] if subtitles else ""290 if "Complet" in subtitles or any("complet" in s.lower() for s in subtitles):291 return None # aucun logement disponible292 price_label = next((s for s in subtitles if "$" in s), "")293 unit_types = [s for s in subtitles294 if re.fullmatch(r"\d\s*½|\d\s*1/2|Studio|Loft", s)]295296 notice = card.select_one(".c-card_notice")297 availability = notice.get_text(" ", strip=True) if notice else ""298 if availability.lower() == "maintenant":299 availability = "Disponible maintenant"300301 # prix plancher : JSON budget-min sinon texte « À partir de … $ »302 price = None303 bmin = str(filters.get("budget-min") or "").strip()304 if bmin.isdigit():305 val = float(bmin)306 if 100 <= val <= 20000:307 price = val308 if price is None:309 price = parse_price(price_label)310311 images = [img.get("src") for img in card.select("img.c-card_image")312 if img.get("src")]313 images = list(dict.fromkeys(images))[:20]314315 sector = ""316 if city == "Montréal":317 for key, sec in _SECTOR_HINTS:318 if key in slug:319 sector = sec320 break321 elif locality and locality != city:322 sector = locality323324 return Listing(325 source=self.source_id,326 external_id=slug,327 url=f"{BASE}/project/{slug}/",328 title=name,329 address=f"{address}, {locality}" if address else locality,330 sector=sector,331 city=city,332 unit_type=", ".join(dict.fromkeys(333 t.replace(" ", "").replace("1/2", "½") for t in unit_types)),334 price=price,335 price_label=price_label,336 availability=availability,337 amenities=[],338 images=images,339 )340