Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/immeubles_aeb.py10# Module : louka11# Repository : https://git.spboucher.ai/lou-ka12# Created : 2026-08-0913# 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/immeubles_aeb.py : connecteur Immeubles AEB (immeublesaeb.com —91# Saguenay : Chicoutimi, Jonquière, Arvida, La Baie, Laterrière + St-Honoré ;92# filiale du Groupe Boudreault). Site custom statique (Bootstrap), tout rendu93# serveur. Liste /logements : cartes `.housing-block` (nom, type « Appartement94# 4 1/2 »/« Loft »/« Chambre », prix « 1380.00$ / mois », secteur, texte de95# disponibilité, photo de couverture en background). Fiche /logements/<slug>96# (via cache BD) : adresse civique (« Coût et localisation »), blocs97# Description structurés (étage, durée du bail, chambres, salles de bain),98# caractéristiques/commodités, « À proximité de » et galerie complète.99# robots.txt géré par Cloudflare : `User-agent: *` → Allow: / avec100# Content-Signal search=yes (l'usage index/agrégateur est permis ; seuls des101# bots d'entraînement IA nommés — ClaudeBot, GPTBot… — sont bloqués, LouKaBot102# n'est pas visé). La page /logement-etudiant est une vitrine sans annonces.103# -----------------------------------------------------------------------------104from __future__ import annotations105106import hashlib107import re108109from bs4 import BeautifulSoup110111from ..schema import Listing, normalize_unit_type, parse_price, strip_accents112from .base import BaseConnector113114BASE = "https://immeublesaeb.com"115LIST_URL = f"{BASE}/logements"116117_BG_URL_RE = re.compile(r"background\s*:\s*url\(([^)]+)\)")118119# secteurs de la ville de Saguenay (le reste = municipalités distinctes)120_SAGUENAY_SECTORS = {"chicoutimi", "jonquiere", "arvida", "la baie", "laterriere"}121122123class ImmeublesAEBConnector(BaseConnector):124 source_id = "immeubles_aeb"125 request_delay = 0.6126 max_details = 30 # garde-fou fiches détail (vraies requêtes par sync)127128 def fetch(self) -> list[Listing]:129 html = self.get(LIST_URL).text130 soup = BeautifulSoup(html, "html.parser")131132 self._fetched = 0133 listings: dict[str, Listing] = {}134 for block in soup.select(".housing-block"):135 try:136 self._parse_card(block, listings)137 except Exception:138 continue139 return list(listings.values())140141 # -- carte (.housing-block) ------------------------------------------------------142 def _parse_card(self, block, listings: dict[str, Listing]) -> None:143 link = block.select_one('a[href*="/logements/"]')144 if not link:145 return146 url = link["href"]147 m = re.search(r"/logements/([^/?#]+)", url)148 if not m:149 return150 ext_id = m.group(1)151 if not ext_id or ext_id in listings:152 return153154 name_el = block.select_one("p.housingName")155 name = name_el.get_text(strip=True) if name_el else ""156 type_el = block.select_one(".content h4")157 unit_label = re.sub(r"\s+", " ",158 type_el.get_text(" ", strip=True)) if type_el else ""159160 # <p> du bloc contenu : prix (« 980.00$ / mois »), secteur (épinglette),161 # disponibilité (icône calendrier)162 price_label = sector = availability = ""163 for p in block.select(".content p"):164 txt = re.sub(r"\s+", " ", p.get_text(" ", strip=True))165 if not txt or p.get("class") == ["housingName"]:166 continue167 if p.select_one("i.fa-map-marker-alt"):168 sector = txt169 elif p.select_one("i.icon-calendar"):170 availability = txt171 elif "$" in txt and not price_label:172 price_label = txt173174 # photo de couverture (background-image de la carte)175 images: list[str] = []176 for el in block.select("[style]"):177 m_bg = _BG_URL_RE.search(el.get("style", ""))178 if m_bg:179 u = m_bg.group(1).strip("'\" ")180 if u.startswith("http") and u not in images:181 images.append(u)182183 city = "Saguenay"184 sec_key = strip_accents(re.sub(r"[-_]", " ", sector.lower())).strip()185 if sec_key and sec_key not in _SAGUENAY_SECTORS:186 city = sector # St-Honoré et autres municipalités distinctes187188 lst = Listing(189 source=self.source_id,190 external_id=ext_id,191 url=url,192 title=name or unit_label,193 sector=sector,194 city=city,195 unit_type=normalize_unit_type(unit_label.replace("Appartement", "").strip()),196 price=parse_price(price_label),197 price_label=price_label,198 availability=availability,199 images=images[:10],200 )201202 key = hashlib.sha1(203 f"{name}|{unit_label}|{price_label}|{availability}|{sector}"204 .encode("utf-8")).hexdigest()205 try:206 payload = self.detail(ext_id, key,207 lambda u=url: self._fetch_detail(u))208 self._apply_detail(lst, payload)209 except Exception:210 pass211 listings[ext_id] = lst212213 # -- fiche détail (/logements/<slug>) --------------------------------------------214 def _fetch_detail(self, url: str) -> dict:215 """Adresse, blocs Description, commodités, proximité et galerie."""216 if self._fetched >= self.max_details:217 raise RuntimeError("budget de fiches détail atteint")218 self._fetched += 1219 html = self.get(url).text220 soup = BeautifulSoup(html, "html.parser")221 out: dict = {}222223 # « Coût et localisation » : adresse civique sous l'épinglette224 addr_el = soup.select_one(".price-location .address p")225 if addr_el:226 out["address"] = re.sub(r"\s+", " ",227 addr_el.get_text(" ", strip=True)).strip(" ,")228229 # blocs Description structurés (étage, bail, chambres, salles de bain)230 traits: list[str] = []231 for box in soup.select(".housing-description .description-box"):232 label_el = box.select_one("p.label")233 val_el = box.select_one("p.content")234 if not label_el or not val_el:235 continue236 label = label_el.get_text(strip=True)237 val = val_el.get_text(strip=True)238 if not val or re.match(r"type|disponibilit", label, re.I):239 continue # type et dispo déjà portés par la carte240 if re.match(r"chambres", label, re.I):241 traits.append(f"{val} chambre(s)")242 elif re.match(r"salles? de bain", label, re.I):243 traits.append(f"{val} salle(s) de bain")244 else:245 traits.append(f"{label} : {val}")246247 # caractéristiques et commodités (chauffé/éclairé, meublé, internet…)248 for li in soup.select(".features .features-content li, "249 ".features .features-content span"):250 txt = re.sub(r"\s+", " ", li.get_text(" ", strip=True))251 if txt:252 traits.append(txt)253 out["amenities"] = traits[:20]254255 # « À proximité de » : texte libre -> description256 near_el = soup.select_one(".close-by .close-by-content")257 if near_el:258 txt = re.sub(r"\s+", " ", near_el.get_text(" ", strip=True))259 if txt:260 out["description"] = txt[:1200]261262 # galerie complète (diaporama en background-image)263 images: list[str] = []264 for el in soup.select(".slider-container[style], .housing-slider [style]"):265 m_bg = _BG_URL_RE.search(el.get("style", ""))266 if m_bg:267 u = m_bg.group(1).strip("'\" ")268 if u.startswith("http") and u not in images:269 images.append(u)270 out["images"] = images[:25]271 return out272273 def _apply_detail(self, lst: Listing, d: dict) -> None:274 """Reporte le payload (frais ou en cache) sur l'annonce."""275 if not d:276 return277 if d.get("address"):278 lst.address = d["address"]279 if d.get("description"):280 lst.description = d["description"]281 if d.get("amenities"):282 lst.amenities = list(dict.fromkeys(lst.amenities + d["amenities"]))283 if d.get("images") and len(d["images"]) > len(lst.images):284 lst.images = d["images"]285