Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/appartements_rimouski.py10# Module : louka11# Repository : https://git.spboucher.ai/lou-ka12# Created : 2026-08-0913# Last Modified : 2026-09-1314#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/appartements_rimouski.py : connecteur Appartements Rimouski91# (Immeubles DTM — appartementsrimouski.com, Rimouski et Le Bic, ~100+92# logements). WordPress multisite + thème Pro (Cornerstone) + plugin Estatik93# pour l'annuaire d'immeubles ; la page « Choisir mon logement »94# /choisir-mon-logement liste les UNITÉS actuellement en location : cartes95# rendues serveur (titre, prix « 725$/mois », disponibilité « Disponible96# maintenant »/« 1 septembre 2026 », adresse complète, chambres/SDB, badge97# Résidentiel/Commercial, photo). Fiche unité /logements/<slug> (via cache98# BD) : description complète, quartier (« Quartier : Rimouski-Est »),99# galerie et GPS via le JSON-LD schema.org/House (lat/lng inversés à la100# source : corrigés). robots.txt : Disallow /pro/* seulement, sitemap XML.101# 2026-09-13 : SiteGround sert son anti-bot sgcaptcha (202 + challenge JS,102# en-tête sg-captcha) aux IP datacenter — invisible du wrapper résilient103# (2xx) ; on bascule alors la session sur un proxy résidentiel Oxylabs CA104# (même pattern que boreal_abitibi/citiluxx/cromwell/deschenes_pepin/105# gestion_habitation/gimcote, hébergeur identique).106# -----------------------------------------------------------------------------107from __future__ import annotations108109import hashlib110import html as htmllib111import json112import os113import re114import time115from urllib.parse import quote116117from bs4 import BeautifulSoup118119from ..schema import Listing, normalize_unit_type, parse_price120from .base import BaseConnector121122BASE = "https://www.appartementsrimouski.com"123LIST_URL = f"{BASE}/choisir-mon-logement"124125# page interstitielle sgcaptcha SiteGround (meta refresh vers /.well-known/…)126_SG_MARKER = "/.well-known/sgcaptcha/"127128129def _sg_challenge(resp) -> bool:130 """True si la réponse est le challenge anti-bot SiteGround (202 + JS)."""131 if "challenge" in str(resp.headers.get("sg-captcha", "")).lower():132 return True133 return _SG_MARKER in (resp.text or "")[:600]134135_PRICE_RE = re.compile(r"\d[\d\s,.]*\$\s*/\s*mois", re.I)136# type explicite dans le titre (« 3 1/2 », « Studio », « Chambre », « Loft »)137_HALF_RE = re.compile(r"(\d+)\s*(?:½|1/2)")138139140def _unit_type_from_title(title: str) -> str:141 """Type d'unité seulement s'il est explicite dans le titre (rien d'inventé)."""142 m = _HALF_RE.search(title)143 if m:144 return normalize_unit_type(m.group(0))145 low = title.lower()146 if "studio" in low:147 return "Studio"148 if "loft" in low:149 return "Loft"150 if re.search(r"\bchambre\b", low):151 return "Chambre"152 return ""153154155def _city_from_address(address: str) -> str:156 """« 94 Rue Notre Dame Est, Rimouski, QC G5L 1Z7, Canada » -> Rimouski."""157 parts = [p.strip() for p in address.split(",") if p.strip()]158 for p in parts[1:]:159 if not re.match(r"^(QC|Qu[ée]bec|Canada|G\d[A-Z])", p, re.I):160 return re.sub(r"\s+(QC|Qu[ée]bec).*$", "", p, flags=re.I).strip()161 return "Rimouski" # parc concentré à Rimouski/Le Bic162163164class AppartementsRimouskiConnector(BaseConnector):165 source_id = "appartements_rimouski"166 request_delay = 0.6167 max_details = 30 # garde-fou fiches détail (vraies requêtes par sync)168169 def _enable_residential_proxy(self) -> bool:170 """Route toute la session via Oxylabs résidentiel CA (session collante)."""171 endpoint = os.environ.get("OXYLABS_PROXY")172 user = os.environ.get("OXYLABS_PROXY_USER")173 pwd = os.environ.get("OXYLABS_PROXY_PASS")174 if not (endpoint and user and pwd):175 return False176 puser = f"{user}-cc-CA-sessid-rimouski{int(time.time())}-sesstime-10"177 proxy = f"http://{quote(puser, safe='')}:{quote(pwd, safe='')}@{endpoint}"178 self.session.proxies = {"http": proxy, "https": proxy}179 self.session.verify = False # CA MITM du proxy Oxylabs180 return True181182 def _get_html(self, url: str) -> str:183 """GET avec contournement du challenge sgcaptcha (proxy résidentiel)."""184 resp = self.get(url)185 if not _sg_challenge(resp):186 return resp.text187 if not self.session.proxies and self._enable_residential_proxy():188 resp = self.get(url)189 if not _sg_challenge(resp):190 return resp.text191 raise RuntimeError(f"challenge sgcaptcha non contourné — {url}")192193 def fetch(self) -> list[Listing]:194 # échec franc sur challenge (fini le « 0 trouvé ok » silencieux)195 html = self._get_html(LIST_URL)196 soup = BeautifulSoup(html, "html.parser")197198 self._fetched = 0199 listings: dict[str, Listing] = {}200 # une carte = un lien /logements/<slug> englobant un <article>201 for a in soup.select('a[href*="/logements/"]'):202 if not a.select_one("article"):203 continue204 try:205 self._parse_card(a, listings)206 except Exception:207 continue208 return list(listings.values())209210 # -- carte (page « Choisir mon logement ») -----------------------------------211 def _parse_card(self, a, listings: dict[str, Listing]) -> None:212 url = a["href"]213 m = re.search(r"/logements/([^/?#]+)", url)214 if not m:215 return216 ext_id = m.group(1)217 if ext_id in listings:218 return219220 art = a.select_one("article")221 title_el = art.select_one("h2")222 title = title_el.get_text(strip=True) if title_el else ""223224 # badge de catégorie (Résidentiel / Commercial) : on écarte le commercial225 badges = [b.get_text(strip=True)226 for b in art.select(".x-anchor-text-primary")]227 if any(re.search(r"commercial|bureau|local", b, re.I) for b in badges):228 return229 # « avec stationnement » est une commodité : n'exclure que les annonces230 # DE stationnement/garage (titre commençant par le mot)231 if re.search(r"commercial|bureau\b|^\s*(stationnement|garage|entreposage|entrep[oô]t)",232 title, re.I):233 return234235 # bandeau de la vignette = disponibilité (« Disponible maintenant »,236 # « 1 septembre 2026 », « Courte durée disponible »)237 avail_el = a.select_one("figure .x-text.x-content")238 availability = avail_el.get_text(strip=True) if avail_el else ""239240 # prix (« 725$/mois ») et adresse : blocs texte de l'article241 price_label, address = "", ""242 for div in art.select(".x-text.x-content"):243 txt = div.get_text(" ", strip=True)244 if not price_label and _PRICE_RE.search(txt):245 price_label = txt246 elif not address and re.search(r",\s*(QC|Qu[ée]bec)\b", txt):247 address = txt248249 # chambres / salles de bain : pastilles structurées de la carte250 amenities: list[str] = []251 for p in art.select("p.x-text-content-text-primary"):252 txt = p.get_text(" ", strip=True)253 if re.search(r"chambre|sdb", txt, re.I):254 amenities.append(txt)255256 img = a.select_one("figure img[src]")257 images = [img["src"]] if img and img["src"].startswith("http") else []258259 lst = Listing(260 source=self.source_id,261 external_id=ext_id,262 url=url,263 title=htmllib.unescape(title),264 address=address,265 city=_city_from_address(address),266 unit_type=_unit_type_from_title(title),267 price=parse_price(price_label),268 price_label=price_label,269 availability=availability,270 amenities=amenities,271 images=images,272 )273274 key = hashlib.sha1(275 f"{title}|{price_label}|{availability}|{address}"276 .encode("utf-8")).hexdigest()277 try:278 payload = self.detail(ext_id, key,279 lambda u=url: self._fetch_detail(u))280 self._apply_detail(lst, payload)281 except Exception:282 pass283 listings[ext_id] = lst284285 # -- fiche unité (/logements/<slug>) -------------------------------------------286 def _fetch_detail(self, url: str) -> dict:287 """Description, quartier, galerie et GPS (JSON-LD schema.org/House)."""288 if self._fetched >= self.max_details:289 raise RuntimeError("budget de fiches détail atteint")290 self._fetched += 1291 # _get_html lève sur challenge : pas de {} vide dans detail_cache292 # (clé figée jamais invalidée)293 html = self._get_html(url)294 soup = BeautifulSoup(html, "html.parser")295 out: dict = {}296297 # description complète (contenu de l'article, thème Pro)298 content = soup.select_one(".x-the-content")299 if content:300 txt = content.get_text("\n", strip=True)301 out["description"] = re.sub(r"[ \t]+", " ", txt).strip()[:1500]302303 # « Quartier : Rimouski-Est » (bloc méta de la fiche)304 m = re.search(r"Quartier\s*:\s*([^\n|]{2,60})",305 soup.get_text("\n", strip=True))306 if m:307 out["sector"] = m.group(1).strip()308309 # JSON-LD schema.org/House : galerie + GPS (lat/lng inversés à la source)310 for script in soup.find_all("script", type="application/ld+json"):311 try:312 data = json.loads(script.get_text())313 except Exception:314 continue315 if not isinstance(data, dict) or data.get("@type") != "House":316 continue317 imgs = data.get("image") or []318 if isinstance(imgs, list):319 out["images"] = [u for u in imgs320 if isinstance(u, str) and u.startswith("http")][:30]321 geo = data.get("geo") or {}322 try:323 lat, lng = float(geo.get("latitude")), float(geo.get("longitude"))324 except (TypeError, ValueError):325 continue326 # le plugin publie latitude/longitude permutés : on remet à l'endroit327 if 44.5 <= lat <= 63.0 and -80.0 <= lng <= -56.0:328 out["lat"], out["lng"] = lat, lng329 elif 44.5 <= lng <= 63.0 and -80.0 <= lat <= -56.0:330 out["lat"], out["lng"] = lng, lat331 return out332333 def _apply_detail(self, lst: Listing, d: dict) -> None:334 """Reporte le payload (frais ou en cache) sur l'annonce."""335 if not d:336 return337 if d.get("description"):338 lst.description = d["description"]339 if d.get("sector"):340 lst.sector = d["sector"]341 if d.get("images") and len(d["images"]) > len(lst.images):342 lst.images = d["images"]343 if d.get("lat") is not None and d.get("lng") is not None:344 lst.lat, lst.lng = d["lat"], d["lng"]345