Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/logement_mauricie.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/logement_mauricie.py : connecteur Logement Mauricie91# (logementmauricie.com) — regroupement de propriétaires (+200 logements).92# Builder type WebSelf : 4 pages secteur (Trois-Rivières, Cap-de-la-93# Madeleine, Shawinigan, Shawinigan-Sud), chaque immeuble = un widget94# texte (id GUID stable) avec champs libellés « Type / Actuellement95# disponible / Date / Chauffé éclairé / Combien $ / Contact… ». On ne96# retient que les immeubles avec une disponibilité réelle (≠ Complet).97# -----------------------------------------------------------------------------98from __future__ import annotations99100import re101from urllib.parse import urljoin102103from bs4 import BeautifulSoup104105from ..schema import Listing, normalize_unit_type, parse_price106from .base import BaseConnector107108BASE = "http://logementmauricie.com"109110# pages secteur -> (ville réelle, secteur) ; Cap-de-la-Madeleine et111# Shawinigan-Sud sont des secteurs des villes fusionnées (2002)112PAGES = [113 ("trois-rivieres", "Trois-Rivières", ""),114 ("cap-de-la-madeleine", "Trois-Rivières", "Cap-de-la-Madeleine"),115 ("shawinigan", "Shawinigan", ""),116 ("shawinigan-sud", "Shawinigan", "Shawinigan-Sud"),117]118119# libellés des champs du gabarit d'immeuble120_LABELS = re.compile(121 r"^(Type|Actuellement disponible|Date|Chauff[ée] [ée]clair[ée]|"122 r"Commodit[ée]s?|Entr[ée]e laveuse et s[ée]cheuse|Stationnements?|"123 r"Plus|Combien \$|Contact)\s*:?\s*$", re.I)124125126def _parse_fields(lines: list[str]) -> dict[str, str]:127 """Paires libellé -> valeur (les valeurs suivent le libellé, ligne(s)128 suivante(s) jusqu'au prochain libellé)."""129 fields: dict[str, list[str]] = {}130 cur: str | None = None131 for ln in lines:132 m = _LABELS.match(ln)133 if m:134 cur = m.group(1).lower()135 fields.setdefault(cur, [])136 elif cur is not None:137 fields[cur].append(ln)138 return {k: " ".join(v).strip() for k, v in fields.items()}139140141class LogementMauricieConnector(BaseConnector):142 source_id = "logement_mauricie"143 request_delay = 0.8144 max_pages = 4 # 4 pages secteur, pas de pagination145146 def fetch(self) -> list[Listing]:147 listings: list[Listing] = []148 for slug, city, sector in PAGES[:self.max_pages]:149 url = f"{BASE}/{slug}/"150 try:151 html = self.get(url).text152 except Exception:153 continue154 soup = BeautifulSoup(html, "html.parser")155 for w in soup.select("div.widget.widget-text[id]"):156 try:157 lst = self._parse_widget(w, url, city, sector)158 except Exception:159 continue160 if lst is not None:161 listings.append(lst)162 return listings163164 def _parse_widget(self, w, page_url: str, city: str,165 sector: str) -> Listing | None:166 txt = w.get_text("\n", strip=True)167 if "Actuellement disponible" not in txt:168 return None # widget décoratif (intro, bandeau…)169 lines = [re.sub(r"\s+", " ", ln).strip()170 for ln in txt.split("\n") if ln.strip()]171 fields = _parse_fields(lines)172173 # disponibilité réelle seulement : « Complet », vide ou « - » = ignoré174 dispo = fields.get("actuellement disponible", "").strip(" - ")175 if not dispo or re.search(r"^complet", dispo, re.I):176 return None177 if re.search(r"commercial|stationnement seulement|local\b", dispo, re.I):178 return None179180 h2 = w.find("h2")181 address = h2.get_text(" ", strip=True) if h2 else ""182 if not address or not re.match(r"\d", address):183 return None # bloc sans adresse civique = pas un immeuble184185 ext_id = w.get("id", "") # GUID du widget, stable dans le builder186 if not ext_id:187 return None188189 date_txt = fields.get("date", "").strip(" - ")190 price_label = fields.get("combien $", "").strip(" - ")191192 # description : bloc de champs + paragraphe descriptif du secteur193 desc_lines = []194 started = False195 for ln in lines:196 if ln == address:197 started = True198 continue199 if started and ln.lower() not in ("revenir en haut",):200 desc_lines.append(ln)201202 images: list[str] = []203 for img in w.find_all("img", src=True):204 src = urljoin(page_url, img["src"])205 if re.search(r"google-maps|icon|logo", src, re.I):206 continue207 if src.startswith("http") and src not in images:208 images.append(src)209210 return Listing(211 source=self.source_id,212 external_id=ext_id,213 url=f"{page_url}#{ext_id}", # pas de fiche individuelle214 title=f"{dispo} — {address}",215 address=address,216 sector=sector,217 city=city,218 unit_type=normalize_unit_type(dispo),219 price=parse_price(price_label),220 price_label=price_label,221 availability=date_txt,222 description="\n".join(desc_lines)[:900],223 images=images[:10],224 )225