Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/sibelanger.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/sibelanger.py : connecteur Société immobilière Bélanger91# (sibelanger.com) — page /appartements-a-louer/ : cartes d'unités avec92# prix, « Disponible dès… », secteur, commodités et carrousel de photos.93# Pages détail (cache BD self.detail) : adresse complète avec code postal,94# superficie (« Plan de l'unité … pi2 »), description riche, commodités95# de l'appartement et de l'immeuble, galerie complète.96# -----------------------------------------------------------------------------97from __future__ import annotations9899import hashlib100import re101102from bs4 import BeautifulSoup103104from ..schema import Listing, infer_city, normalize_unit_type, parse_price105from .base import BaseConnector106107BASE = "https://sibelanger.com"108LIST_URL = f"{BASE}/appartements-a-louer/"109110IMG_RE = re.compile(111 r"https://sibelanger\.com/app/uploads/[^\"'\\\s\)]+"112 r"\.(?:jpg|jpeg|png|webp)", re.I)113IMG_NOISE_RE = re.compile(r"logo|favicon|icon|sib_ico", re.I)114115116class SibelangerConnector(BaseConnector):117 source_id = "sibelanger"118 request_delay = 0.6119 max_details = 60 # garde-fou120121 def fetch(self) -> list[Listing]:122 html = self.get(LIST_URL).text123 soup = BeautifulSoup(html, "html.parser")124125 listings: dict[str, Listing] = {}126 for card in soup.select("div.listing__thumbnail"):127 try:128 lst = self._parse_card(card)129 except Exception:130 continue131 if lst and lst.external_id not in listings:132 listings[lst.external_id] = lst133134 # Pages détail (cache BD) : adresse complète, superficie, description,135 # commodités, galerie complète136 fetched = 0137 for i, lst in enumerate(listings.values()):138 if i >= self.max_details:139 break140 key = hashlib.sha1(141 f"{lst.title}|{lst.price_label}|{lst.availability}"142 .encode("utf-8")).hexdigest()143144 def _fetch(url=lst.url):145 nonlocal fetched146 if fetched >= self.max_details:147 raise RuntimeError("plafond de requêtes détail atteint")148 fetched += 1149 return self._fetch_detail(url)150151 try:152 payload = self.detail(lst.external_id, key, _fetch)153 except Exception:154 payload = {}155 if payload:156 self._apply_detail(lst, payload)157158 return list(listings.values())159160 def _parse_card(self, card) -> Listing | None:161 link = card.select_one("a.listing__thumbnail__content__title-wrapper") \162 or card.select_one("a[href*='/appartements-a-louer/']")163 if not link:164 return None165 url = link.get("href", "").split("?")[0]166 m = re.search(r"/appartements-a-louer/([a-z0-9\-]+)/?$", url)167 if not m:168 return None169 slug = m.group(1)170171 fav = card.select_one("[data-unit-id]")172 ext_id = (fav.get("data-unit-id", "").strip() if fav else "") or slug173174 h3 = card.select_one("h3")175 title = h3.get_text(" ", strip=True) if h3 else slug176 sector_el = card.select_one(177 ".listing__thumbnail__content__title-wrapper p")178 sector = sector_el.get_text(strip=True) if sector_el else ""179180 price_el = card.select_one(".listing__thumbnail__price")181 price_label = price_el.get_text(" ", strip=True) if price_el else ""182 avail_el = card.select_one(".listing__thumbnail__availability")183 avail = avail_el.get_text(" ", strip=True) if avail_el else ""184 size_el = card.select_one(".listing__thumbnail__size")185 unit_raw = size_el.get_text(" ", strip=True) if size_el else ""186187 # Exclusions (prudence : le site est résidentiel)188 if re.search(r"stationnement|commercial|rangement|entrepos",189 f"{title} {unit_raw}", re.I):190 return None191192 # Adresse dérivée du slug : « 350-101-chemin-ste-foy-… » ->193 # « 350, Chemin Ste-Foy » (n° d'immeuble, n° d'unité, rue)194 address = ""195 s = re.sub(r"^copie-de-", "", slug)196 ma = re.match(r"^(\d+)-\d+[a-z]?-([a-z\-]+?)"197 r"(?:-selection|-modele|-app|$)", s)198 if ma:199 street = " ".join(w.capitalize() for w in ma.group(2).split("-"))200 address = f"{ma.group(1)}, {street}"201202 amenities = [img.get("title") or img.get("alt", "")203 for img in card.select(204 ".listing__thumbnail__content__features img")]205 amenities = [a.strip() for a in amenities if a and a.strip()]206207 images = []208 for img in card.select(".swiper-slide img"):209 src = img.get("src") or img.get("data-src") or ""210 if src.startswith("http") and not IMG_NOISE_RE.search(src):211 images.append(src)212213 return Listing(214 source=self.source_id,215 external_id=ext_id,216 url=url,217 title=title,218 address=address,219 sector=sector,220 city=infer_city(sector),221 unit_type=normalize_unit_type(unit_raw),222 price=parse_price(price_label),223 price_label=price_label,224 availability=avail,225 amenities=amenities,226 images=list(dict.fromkeys(images)),227 )228229 def _fetch_detail(self, url: str) -> dict:230 """Télécharge une page détail et en extrait le payload brut (cacheable)."""231 html = self.get(url).text232 soup = BeautifulSoup(html, "html.parser")233234 # entête : adresse complète (code postal) + disponibilité235 address = availability = ""236 info = soup.select_one("div.single-unit__info")237 if info:238 paras = [p.get_text(" ", strip=True) for p in info.select("p")]239 for t in paras:240 if not address and re.search(r"\d.+(?:Québec|Lévis|G\d[A-Z]\s?\d[A-Z]\d)", t):241 address = t242 elif re.search(r"Disponible|Libre|Loué", t, re.I):243 availability = t.strip(" .")244245 # description riche (sans les invites « Demander une visite »)246 desc = ""247 sec = soup.select_one("section.single-unit__description")248 if sec:249 desc = re.sub(r"\s+", " ", sec.get_text(" ", strip=True))250 desc = re.sub(r"Cliquer sur le lien ici pour\s*(Demander une visite)?\s*",251 "", desc).strip()252 if not desc:253 og = soup.find("meta", attrs={"property": "og:description"}) or \254 soup.find("meta", attrs={"name": "description"})255 if og and og.get("content"):256 desc = og["content"].strip()257258 # superficie affichée sous le plan (« 1360 pi2 ») — texte brut,259 # normalisé ensuite par finalize()260 surf_el = soup.select_one("span.single-unit__plan-surface")261 surface = surf_el.get_text(" ", strip=True) if surf_el else ""262263 # caractéristiques de l'appartement + commodités de l'immeuble264 # (les « Services de proximité » — épicerie, parc… — sont exclus)265 amenities: list[str] = []266 for section in soup.select("section.single-unit__features"):267 title_el = section.select_one("h2")268 title = title_el.get_text(" ", strip=True) if title_el else ""269 if re.search(r"proximit", title, re.I):270 continue271 for li in section.select("li"):272 t = li.get_text(" ", strip=True)273 if t and len(t) < 60 and t not in amenities:274 amenities.append(t)275276 images = [u for u in dict.fromkeys(IMG_RE.findall(html))277 if not IMG_NOISE_RE.search(u)278 and not re.search(r"-\d+x\d+\.", u)]279280 return {"address": address, "availability": availability,281 "description": desc[:800], "surface": surface,282 "amenities": amenities, "images": images}283284 def _apply_detail(self, lst: Listing, payload: dict) -> None:285 """Applique le payload d'une page détail (frais ou depuis le cache)."""286 if payload.get("address"):287 lst.address = payload["address"]288 if payload.get("availability") and not lst.availability:289 lst.availability = payload["availability"]290 if payload.get("description"):291 lst.description = payload["description"]292 # superficie : texte source (« 1360 pi2 ») ajouté aux commodités pour293 # affichage + parsing par finalize()294 extra = list(payload.get("amenities") or [])295 if payload.get("surface"):296 extra.append(payload["surface"])297 lst.amenities = list(dict.fromkeys(lst.amenities + extra))298 merged = list(dict.fromkeys((payload.get("images") or []) + lst.images))299 if merged:300 lst.images = merged[:25]301