Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/immo_3r.py10# Module : louka11# Repository : https://git.spboucher.ai/lou-ka12# Created : 2026-08-2513# Last Modified : 2026-08-2514#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/immo_3r.py : connecteur IMMO 3R (immo3r.com)91# Gestion immobilière locative en Mauricie / Centre-du-Québec :92# Trois-Rivières (Cap-de-la-Madeleine), Shawinigan, Bécancour, Nicolet,93# Saint-Maurice. WordPress rendu serveur : pages ville /location/<ville>/94# avec cartes (type, rue, ville, prix, badge dispo-oui/dispo-non) ; pages95# détail /apartments/<slug>/ avec JSON-LD schema.org (Offer → Apartment :96# adresse postale complète, description, commodités, photos).97# Granularité : une fiche par modèle d'appartement (adresse + typologie),98# pas par unité individuelle.99# -----------------------------------------------------------------------------100from __future__ import annotations101102import hashlib103import json104import re105106from bs4 import BeautifulSoup107108from ..schema import Listing, normalize_unit_type109from .base import BaseConnector110111BASE = "https://immo3r.com"112113# Pages ville (rendues serveur, toutes les cartes présentes dans le HTML)114CITY_PAGES = [115 (f"{BASE}/location/trois-rivieres/", "Trois-Rivières"),116 (f"{BASE}/location/shawinigan/", "Shawinigan"),117 (f"{BASE}/location/becancour/", "Bécancour"),118 (f"{BASE}/location/nicolet/", "Nicolet"),119 (f"{BASE}/location/saint-maurice/", "Saint-Maurice"),120]121122# Badges de disponibilité conservés (cartes) — « En construction » et123# « Non disponible » = pas louable maintenant, on exclut.124KEEP_STATUS = {"disponible", "bientôt disponible", "bientot disponible"}125126PRICE_RE = re.compile(r"([\d\s ,]+)\s*\$")127IMG_JUNK_RE = re.compile(r"logo|icon|favicon|-\d{2,3}x\d{2,3}\.", re.I)128129130class Immo3RConnector(BaseConnector):131 source_id = "immo_3r"132 request_delay = 0.7133134 def fetch(self) -> list[Listing]:135 listings: list[Listing] = []136 seen: set[str] = set()137 for page_url, city in CITY_PAGES:138 try:139 html = self.get(page_url).text140 except Exception:141 continue142 soup = BeautifulSoup(html, "html.parser")143 for a in soup.select('a[href*="/apartments/"]'):144 try:145 card = a.select_one("article.apartment-single")146 if card is None:147 continue148 url = a.get("href", "").split("?")[0]149 slug = url.rstrip("/").split("/")[-1]150 if not slug or slug in seen:151 continue152153 status_el = card.select_one(".dispo-oui, .dispo-non")154 status = (status_el.get_text(" ", strip=True)155 if status_el else "")156 if status.strip().lower() not in KEEP_STATUS:157 continue158 seen.add(slug)159160 # type d'unité : badge « 5 1/2 » (ou le titre en secours)161 rooms_el = card.select_one(".apartment-single__rooms")162 sector_el = card.select_one(".apartment-single__sector")163 title_txt = (sector_el.get_text(" ", strip=True)164 if sector_el else "")165 unit_type = normalize_unit_type(166 rooms_el.get_text(" ", strip=True) if rooms_el167 else title_txt)168169 # « Rue des Prairies, Trois-Rivières » (2e span du titre)170 street = ""171 h2 = card.select_one(".apartment-single__title")172 if h2 is not None:173 spans = [s for s in h2.find_all("span", recursive=False)174 if "apartment-single__sector"175 not in (s.get("class") or [])]176 if spans:177 street = spans[0].get_text(" ", strip=True)178 street = re.sub(r"\s*,\s*" + re.escape(city) + r"$",179 "", street).strip(" ,")180181 price = None182 price_label = ""183 price_el = card.select_one(".apartment-single__price")184 if price_el is not None:185 price_label = re.sub(r"\s+", " ",186 price_el.get_text(" ", strip=True))187 m = PRICE_RE.search(price_label)188 if m:189 try:190 price = float(m.group(1)191 .replace(" ", "")192 .replace(" ", "")193 .replace(",", ""))194 except ValueError:195 pass196197 # page détail (JSON-LD) via cache BD — revisitée198 # seulement si la carte liste a changé199 card_key = hashlib.sha1(200 f"{status}|{price_label}|{title_txt}|{street}"201 .encode("utf-8")).hexdigest()202 d = self.detail(slug, card_key,203 lambda url=url: self._fetch_detail(url))204205 title = d.get("name") or title_txt or slug206 address = d.get("address") or street207 listings.append(Listing(208 source=self.source_id,209 external_id=slug,210 url=url,211 title=title,212 address=address,213 sector=d.get("sector", ""),214 city=d.get("city") or city,215 unit_type=unit_type,216 price=price if price is not None else d.get("price"),217 price_label=price_label,218 availability=status,219 description=d.get("description", ""),220 amenities=d.get("amenities") or [],221 images=d.get("images") or [],222 ))223 except Exception:224 continue225 return listings226227 def _fetch_detail(self, url: str) -> dict:228 """Champs riches depuis le JSON-LD `Offer` de la page détail :229 adresse postale, secteur, description, prix, commodités, photos."""230 out: dict = {}231 try:232 html = self.get(url).text233 except Exception:234 return out235 offer = None236 for m in re.finditer(237 r'<script type="application/ld\+json"[^>]*>([\s\S]*?)</script>',238 html):239 try:240 data = json.loads(m.group(1))241 except ValueError:242 continue243 if isinstance(data, dict) and data.get("@type") == "Offer" \244 and isinstance(data.get("itemOffered"), dict):245 offer = data246 break247 if offer is None:248 return out249 apt = offer.get("itemOffered") or {}250 out["name"] = (apt.get("name") or "").strip()251 addr = apt.get("address") or {}252 street = (addr.get("streetAddress") or "").strip()253 if street:254 out["address"] = street255 if addr.get("addressLocality"):256 out["city"] = addr["addressLocality"].strip()257 out["description"] = (offer.get("description") or "").strip()[:900]258 out["amenities"] = [259 f["name"].strip() for f in (apt.get("amenityFeature") or [])260 if isinstance(f, dict) and f.get("name") and f.get("value")][:25]261 spec = offer.get("priceSpecification") or {}262 try:263 out["price"] = float(spec.get("price"))264 except (TypeError, ValueError):265 pass266 for prop in offer.get("additionalProperty") or []:267 if isinstance(prop, dict) and prop.get("name") == "Secteur":268 out["sector"] = (prop.get("value") or "").strip()269 imgs = offer.get("image") or []270 if isinstance(imgs, str):271 imgs = [imgs]272 out["images"] = [u for u in dict.fromkeys(imgs)273 if isinstance(u, str) and not IMG_JUNK_RE.search(u)][:25]274 return out275