Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/immomarketing.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/immomarketing.py : connecteur IMMOMARKETING / Immoappart91# (immoappart.ca). Le portail couvre la région de Québec ET le Grand92# Montréal (île de Montréal, Laval, Longueuil/Rive-Sud) : on crawle les93# pages de secteurs (les plus précises d'abord pour un meilleur secteur).94# Une annonce par unité (fiche /appartement/<slug>/) ; les fiches passent95# par le cache BD self.detail() (clé = hash de la carte liste) : seules96# les fiches nouvelles ou modifiées sont re-téléchargées.97# -----------------------------------------------------------------------------98from __future__ import annotations99100import hashlib101import re102103from bs4 import BeautifulSoup104105from ..schema import (Listing, infer_city, normalize_unit_type, parse_price,106 strip_accents)107from .base import BaseConnector108109BASE = "https://immoappart.ca"110# page de secteur -> (secteur par défaut, ville par défaut). Ordre important :111# pages précises d'abord (le premier secteur rencontré est conservé).112SECTOR_PAGES = {113 # Région de Québec114 f"{BASE}/appartements-a-louer/quebec/lebourgneuf/": ("Lebourgneuf", "Québec"),115 f"{BASE}/appartements-a-louer/quebec/saint-roch-2/": ("Saint-Roch", "Québec"),116 # Île de Montréal117 f"{BASE}/appartements-a-louer/montreal/ahuntsic-cartierville/":118 ("Ahuntsic-Cartierville", "Montréal"),119 f"{BASE}/appartements-a-louer/montreal/cote-des-neiges/":120 ("Côte-des-Neiges", "Montréal"),121 f"{BASE}/appartements-a-louer/montreal/saint-leonard/":122 ("Saint-Léonard", "Montréal"),123 f"{BASE}/appartements-a-louer/saint-laurent/": ("Saint-Laurent", "Montréal"),124 f"{BASE}/appartements-a-louer/montreal/": ("", "Montréal"),125 # Laval126 f"{BASE}/appartements-a-louer/laval/": ("", "Laval"),127 # Rive-Sud (page agrégée en dernier : villes déduites fiche par fiche)128 f"{BASE}/appartements-a-louer/saint-lambert/": ("", "Saint-Lambert"),129 f"{BASE}/appartements-a-louer/longueuil/": ("", "Longueuil"),130 f"{BASE}/appartements-a-louer/rive-sud/": ("", ""),131}132# secteur affiché sur la fiche (bandeau .city) -> vraie ville, hors région Qc133_SECTOR_CITY = {134 "montreal": "Montréal", "ahuntsic": "Montréal",135 "ahuntsic-cartierville": "Montréal", "cote-des-neiges": "Montréal",136 "saint-leonard": "Montréal", "saint-laurent": "Montréal",137 "ville saint-laurent": "Montréal",138 "laval": "Laval",139 "longueuil": "Longueuil", "saint-hubert": "Longueuil",140 "greenfield park": "Longueuil", "vieux-longueuil": "Longueuil",141 "saint-lambert": "Saint-Lambert", "brossard": "Brossard",142 "boucherville": "Boucherville", "chambly": "Chambly",143 "candiac": "Candiac", "la prairie": "La Prairie",144 "richelieu": "Richelieu", "mcmasterville": "McMasterville",145 "saint-bruno": "Saint-Bruno-de-Montarville",146 "saint-bruno-de-montarville": "Saint-Bruno-de-Montarville",147 "saint-hilaire": "Mont-Saint-Hilaire",148 "mont-saint-hilaire": "Mont-Saint-Hilaire",149 "sainte-julie": "Sainte-Julie", "varennes": "Varennes",150 "beloeil": "Belœil",151}152IMG_RE = re.compile(r"https://immoappart\.ca/wp-content/uploads/"153 r'[^"\s\\)]+\.(?:jpe?g|png|webp)', re.I)154155156class ImmomarketingConnector(BaseConnector):157 source_id = "immomarketing"158 request_delay = 0.6159 max_details = 120 # garde-fou de fetch des fiches (Qc + Grand Mtl)160161 def fetch(self) -> list[Listing]:162 # 1) Fiches référencées par les pages de secteurs (Qc + Grand Mtl).163 # La carte liste (adresse, prix, type, badge) sert de clé de cache :164 # la fiche n'est re-téléchargée que si sa carte a changé.165 pages: dict[str, tuple[str, str, str]] = {} # url -> (secteur, ville, clé)166 for sector_url, (sector, city) in SECTOR_PAGES.items():167 try:168 html = self.get(sector_url).text169 except Exception:170 continue171 soup = BeautifulSoup(html, "html.parser")172 for a in soup.select('a[href*="/appartement/"]'):173 href = (a.get("href") or "").split("?")[0]174 if not re.search(r"/appartement/[a-z0-9\-]+/?$", href):175 continue176 card_txt = re.sub(r"\s+", " ", a.get_text(" ", strip=True))177 key = hashlib.sha1(card_txt.encode("utf-8")).hexdigest()[:20]178 pages.setdefault(href.rstrip("/") + "/", (sector, city, key))179180 # 2) Fiches détaillées (via le cache BD ; budget de vraies requêtes)181 self._fetched = 0182 listings: list[Listing] = []183 for url, (sector, city, key) in pages.items():184 slug = url.rstrip("/").split("/")[-1]185 try:186 payload = self.detail(slug, key,187 lambda u=url: self._fetch_detail(u))188 except Exception:189 continue190 if not payload: # fiche commerciale / stationnement / rangement191 continue192 try:193 listings.append(self._build(url, slug, sector, city, payload))194 except Exception:195 continue196 return listings197198 # -- fiche détaillée -> payload JSON-sérialisable (mis en cache) ------------199 def _fetch_detail(self, url: str) -> dict:200 if self._fetched >= self.max_details:201 raise RuntimeError("budget de requêtes détail atteint")202 self._fetched += 1203 html = self.get(url).text204 soup = BeautifulSoup(html, "html.parser")205206 h1 = soup.find("h1")207 title = h1.get_text(" ", strip=True) if h1 else ""208 if re.search(r"Commercial|Stationnement|Rangement", title, re.I):209 return {}210211 # Bandeau : secteur / type / prix / disponibilité212 band = soup.select_one("p.selected-appart-title")213 band_sector = unit_type = price_label = ""214 if band:215 size = band.select_one(".size")216 unit_type = size.get_text(strip=True) if size else ""217 price = band.select_one(".price")218 price_label = price.get_text(strip=True) if price else ""219 city_el = band.select_one(".city")220 if city_el:221 band_sector = city_el.get_text(strip=True)222223 availability = ""224 for s in soup.find_all(string=re.compile("Date de disponibilité")):225 parent = s.find_parent("p")226 if parent:227 cand = re.sub(r".*Date de disponibilité\s*:?\s*", "",228 parent.get_text(" ", strip=True)).strip()229 if cand:230 availability = cand231 break232233 # Adresse : h2 sous le h1234 address = ""235 for h2 in soup.find_all("h2"):236 t = re.sub(r"\s+", " ", h2.get_text(" ", strip=True))237 if re.match(r"^\d{1,5},?\s+\S[^,]{1,60},", t):238 address = t239 break240 if not address:241 # h2 « numéro + rue » sans virgule finale (ex. « 570, Charest est »)242 for h2 in soup.find_all("h2"):243 t = re.sub(r"\s+", " ", h2.get_text(" ", strip=True))244 if len(t) <= 70 and re.match(r"^\d{1,5},?\s+\S", t) \245 and not re.search(r"mois|gratuit|offre|promo|rabais",246 t, re.I):247 address = t248 break249 if not address:250 m = re.search(r"(?<![\d½])\b\d{2,5}\s+(?:rue|boulevard|avenue|"251 r"chemin|côte)[^,<>]{2,50},\s*[^,<>]{2,40},\s*QC",252 re.sub(r"\s+", " ", soup.get_text(" ", strip=True)),253 re.I)254 if m:255 address = m.group(0)256 if not address:257 # dernier recours : le titre commence parfois par l'adresse258 m = re.match(r"^(\d{1,5},?\s+.{3,60}?)\s+[-–]\s+\d\s*½", title)259 if m:260 address = m.group(1).strip()261262 # Photos : galerie de la fiche (éviter les fiches « même secteur »)263 images: list[str] = []264 gallery = soup.select_one(".appart-gallery") or soup265 for el in gallery.select("img[src], a[href]"):266 u = (el.get("src") or el.get("href") or "").split("?")[0]267 if IMG_RE.match(u) and not re.search(r"logo|icon|favicon", u, re.I):268 images.append(u)269 banner = soup.select_one(".banner-appart img[src]")270 if banner:271 images.insert(0, banner["src"].split("?")[0])272 images = list(dict.fromkeys(images))[:25]273274 # Description complète (.the-content : promotions, inclusions de275 # loisirs, informations supplémentaires — animaux, fumeur, contact)276 desc = ""277 content = soup.select_one(".the-content")278 if content:279 desc = re.sub(r"\s+", " ",280 content.get_text(" ", strip=True)).strip()[:1800]281 if not desc:282 og = soup.find("meta", attrs={"property": "og:description"})283 desc = og["content"].strip()[:600] if og and og.get("content") else ""284285 # Commodités : liste « Inclusions » (dropdown dédié de la fiche)286 amenities: list[str] = []287 specs: dict[str, str] = {}288 for dd in soup.select(".single-dropdown"):289 trig = dd.select_one(".trigger")290 label = trig.get_text(strip=True).lower() if trig else ""291 for li in dd.select("li"):292 t = re.sub(r"\s+", " ", li.get_text(" ", strip=True))293 if not t:294 continue295 m = re.match(r"^([\w' éèêàâîôû-]{2,25})\s*:\s*(.+)$", t)296 if "caractéristiques" in label and m:297 specs[m.group(1).strip().lower()] = m.group(2).strip()298 elif "inclusion" in label and 3 < len(t) < 80:299 amenities.append(t)300 if not amenities:301 # repli : listes à puces de la section descriptive302 for li in soup.select("main li"):303 t = re.sub(r"\s+", " ", li.get_text(" ", strip=True))304 if t and 3 < len(t) < 80 and "http" not in t and ":" not in t:305 amenities.append(t)306 amenities = list(dict.fromkeys(amenities))[:15]307308 # Coordonnées GPS de la carte interactive de la fiche309 lat = lng = None310 map_el = soup.select_one("[data-lat][data-lng]")311 if map_el:312 try:313 lat = float(map_el["data-lat"])314 lng = float(map_el["data-lng"])315 except (ValueError, KeyError):316 lat = lng = None317318 return {319 "title": title, "band_sector": band_sector,320 "unit_type": unit_type, "price_label": price_label,321 "availability": availability, "address": address,322 "description": desc, "amenities": amenities, "specs": specs,323 "images": images, "lat": lat, "lng": lng,324 }325326 # -- payload -> Listing ------------------------------------------------------327 def _build(self, url: str, slug: str, sector: str, page_city: str,328 payload: dict) -> Listing:329 if payload.get("band_sector"):330 sector = payload["band_sector"]331 address = payload.get("address", "")332333 # ville : secteur du bandeau s'il correspond à une ville du Grand334 # Montréal, sinon ville de la page de secteur, sinon adresse/Québec335 key = strip_accents((sector or "").strip().lower())336 if key in _SECTOR_CITY:337 city = _SECTOR_CITY[key]338 elif page_city:339 city = infer_city(sector, default=page_city)340 else:341 # page agrégée (ex. Rive-Sud) : dernier segment de l'adresse342 city = ""343 if address:344 parts = [p.strip() for p in address.split(",")345 if p.strip() and not re.fullmatch(346 r"QC|Qu[ée]bec", p.strip(), re.I)]347 if len(parts) >= 2 and not parts[-1][:1].isdigit():348 city = parts[-1]349 city = city or infer_city(sector, default="Québec")350 if sector and sector.lower() == city.lower():351 sector = "" # éviter secteur == ville (redondant)352353 # spécifications structurées (chambres, salles de bain) -> description354 specs = payload.get("specs") or {}355 desc = payload.get("description", "")356 bits = []357 if specs.get("chambre"):358 bits.append(f"{specs['chambre']} chambre(s)")359 if specs.get("salle de bain"):360 bits.append(f"{specs['salle de bain']} salle(s) de bain")361 if bits:362 desc = (desc + " — " if desc else "") + ", ".join(bits) + "."363364 price_label = payload.get("price_label") or specs.get("prix", "")365 unit_type = payload.get("unit_type") or specs.get("pièces", "")366367 return Listing(368 source=self.source_id,369 external_id=slug,370 url=url,371 title=payload.get("title") or slug,372 address=address,373 sector=sector,374 city=city,375 unit_type=normalize_unit_type(unit_type),376 price=parse_price(price_label),377 price_label=price_label,378 availability=payload.get("availability", ""),379 description=desc,380 amenities=list(payload.get("amenities") or []),381 images=list(payload.get("images") or []),382 lat=payload.get("lat"),383 lng=payload.get("lng"),384 )385