Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/app_urbains.py10# Module : louka11# Repository : https://git.spboucher.ai/lou-ka12# Created : 2026-08-0613# Last Modified : 2026-08-0814#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/app_urbains.py : connecteur Appartements Urbains91# (appartementsurbains.ca — Ste-Foy, Montcalm, Limoilou, Loretteville, Lévis)92# Pages projets (Oxygen/WP) : tableau d'unités disponibles avec liens93# « /unites/?_unite=NNN ». Une annonce par unité disponible.94# -----------------------------------------------------------------------------95from __future__ import annotations9697import re98from urllib.parse import unquote99100from bs4 import BeautifulSoup101102from ..schema import Listing, infer_city, normalize_unit_type, parse_price103from .base import BaseConnector104105BASE = "https://www.appartementsurbains.ca"106LIST_URL = f"{BASE}/projets-residentiels/"107108KNOWN_SECTORS = ("Montcalm", "Limoilou", "Lévis", "Ste-Foy", "Loretteville",109 "Sainte-Foy", "Saint-Roch", "Lebourgneuf")110111ADDR_RE = re.compile(112 r"\d{1,5}[^,<>|]{2,60},\s*(?:Lévis|Québec)\s*,?\s*(?:QC|Qu[ée]bec)?"113 r"[^.<>|]{0,15}[A-Z]\d[A-Z]\s?\d[A-Z]\d"114)115# adresse plus permissive (sans code postal) pour la carte-projet wpgb116ADDR_LOOSE_RE = re.compile(117 r"\d{1,5}[^,<>|]{2,60},\s*(?:Lévis|Québec)\b[^.<>|]{0,25}")118AREA_RE = re.compile(r"(\d[\d\s]{1,6})\s*pi[²2]", re.I)119IMG_RE = re.compile(r'https?://[^"\s\\)]+/wp-content/uploads/[^"\s\\)]+'120 r"\.(?:jpe?g|png|webp)", re.I)121BAD_IMG_RE = re.compile(r"favicon|logo|icon|cropped-|social|plugins|hqdefault|"122 r"pdf|texture", re.I)123TYPE_RE = re.compile(r"\d\s*½(?:\s*\+\s*\w+)?|\d\s*1/2|Studio|Loft", re.I)124125126class AppartementsUrbainsConnector(BaseConnector):127 source_id = "app_urbains"128 request_delay = 0.6129 max_projects = 20 # garde-fou de crawl130131 def _discover_projects(self) -> dict[str, dict]:132 """Menu de navigation : « Nom du projet » + « Quartier »."""133 projects: dict[str, dict] = {}134 html = self.get(LIST_URL).text135 soup = BeautifulSoup(html, "html.parser")136 for a in soup.select(f'a[href^="{BASE}/"], a[href^="/"]'):137 href = a.get("href") or ""138 if href.startswith("/"):139 href = BASE + href140 href = href.split("?")[0].rstrip("/")141 slug = href.replace(BASE, "").strip("/")142 # les pages projets sont à la racine (un seul segment, pas de section connue)143 if (not slug or "/" in slug or slug in144 ("projets-residentiels", "nouveaux-projets", "quartiers",145 "a-propos", "actualites", "carrieres", "nous-joindre",146 "html-sitemap", "projets-commerciaux")):147 continue148 text = re.sub(r"\s+", " ", a.get_text(" ", strip=True))149 sector = ""150 for s in KNOWN_SECTORS:151 if re.search(rf"{re.escape(s)}\s*$", text):152 sector = s153 break154 if not sector: # lien sans étiquette de quartier -> ignorer155 continue156 name = text[: -len(sector)].strip()157 if slug not in projects and name:158 projects[slug] = {"name": name, "sector": sector}159 return projects160161 def fetch(self) -> list[Listing]:162 listings: list[Listing] = []163 try:164 projects = self._discover_projects()165 except Exception:166 return listings167168 for i, (slug, meta) in enumerate(projects.items()):169 if i >= self.max_projects:170 break171 url = f"{BASE}/{slug}/"172 try:173 html = self.get(url).text174 except Exception:175 continue176 soup = BeautifulSoup(html, "html.parser")177 text = re.sub(r"\s+", " ", soup.get_text(" ", strip=True))178179 # Adresse : de préférence la carte wpgb du projet lui-même180 # (la 1re adresse de la page peut être un point d'intérêt voisin)181 address = ""182 for card in soup.select(".wpgb-card"):183 card_text = re.sub(r"\s+", " ", card.get_text(" ", strip=True))184 if card_text.lower().startswith(meta["name"].lower()):185 am_ = ADDR_RE.search(card_text) or \186 ADDR_LOOSE_RE.search(card_text)187 if am_:188 address = am_.group(0).strip(" ,")189 break190 if not address:191 m = ADDR_RE.search(text)192 address = m.group(0).strip() if m else ""193 sector = meta["sector"]194 city = infer_city(sector)195 if "Lévis" in address:196 city = "Lévis"197198 # Images du projet (souvent servies depuis le domaine du projet)199 images = [u for u in dict.fromkeys(200 IMG_RE.findall(html) +201 re.findall(r'data-lazy-src="([^"]+\.(?:jpe?g|png|webp))"', html, re.I))202 if not BAD_IMG_RE.search(u)]203 images = [u if u.startswith("http") else BASE + u for u in images][:25]204205 og = soup.find("meta", attrs={"property": "og:description"})206 desc = og["content"].strip()[:600] if og and og.get("content") else ""207208 # Commodités (blocs « avantages » — deux générations de gabarits)209 amenities = list(dict.fromkeys(210 [re.sub(r"\s+", " ", h.get_text(" ", strip=True))211 for h in soup.select(".listing-avantages h4")212 if h.get_text(strip=True)] +213 [s.get_text(strip=True)214 for s in soup.select("div.ct-div-block.c-center span.ct-span")215 if s.get_text(strip=True)]))[:15]216217 # Téléphone du projet (lien tel: structuré) -> details.contact218 details: dict = {}219 tel = soup.select_one('a[href^="tel:"]')220 if tel:221 digits = re.sub(r"\D", "", unquote(tel.get("href", "")))[-10:]222 if len(digits) == 10:223 details["contact"] = {"phone": "-".join(224 (digits[:3], digits[3:6], digits[6:]))}225226 # Tableau des unités disponibles227 seen: set[str] = set()228 for a in soup.select('a[href*="_unite="]'):229 try:230 num = a.get_text(strip=True)231 if not num or num in seen:232 continue233 seen.add(num)234 row = a235 row_text = ""236 for _ in range(4):237 row = row.parent238 if row is None:239 break240 cls = " ".join(row.get("class") or [])241 if "c-full-width" in cls and "flex-row" in cls:242 row_text = re.sub(r"\s+", " ",243 row.get_text(" ", strip=True))244 break245 tm = TYPE_RE.search(row_text)246 unit_type = tm.group(0) if tm else ""247 pm = re.search(r"Prix\s*([\d\s]+\$)", row_text)248 price_label = pm.group(1).strip() if pm else ""249 am = re.search(250 r"Disponibilité\s+(.*?)(?:\s+Superficie|\s+Prix|$)",251 row_text)252 availability = am.group(1).strip() if am else ""253 # Superficie de l'unité (colonne « Superficie (pi²) ») :254 # texte brut dans amenities — finalize() dérive area_sqft255 unit_amenities = amenities256 sqm = AREA_RE.search(row_text)257 if sqm:258 unit_amenities = amenities + [259 f"{sqm.group(1).strip()} pi²"]260 listings.append(Listing(261 source=self.source_id,262 external_id=f"{slug}-{num}",263 url=url,264 title=f"{meta['name']} — unité {num}",265 address=address,266 sector=sector,267 city=city,268 unit_type=normalize_unit_type(unit_type),269 price=parse_price(price_label),270 price_label=price_label,271 availability=availability,272 description=desc,273 amenities=unit_amenities,274 details=dict(details),275 images=images,276 ))277 except Exception:278 continue279280 return listings281