Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/gestion_habitation.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/gestion_habitation.py : connecteur Gestion Habitation91# (gestionhabitation.ca — Abitibi-Témiscamingue : Val-d'Or, Amos, Malartic ;92# seul gestionnaire structuré couvrant Amos). WordPress + Oxygen Builder +93# WP Grid Builder, tout rendu serveur. Liste /a-louer/ : cartes94# `.location-card` (adresse, n° de porte, ville, secteur, disponibilité95# « DISPONIBLE » / « juin 2026 » / « NON DISPONIBLE », prix « 900$/mois ») —96# les cartes « NON DISPONIBLE » (logements loués) sont exclues. Fiche détail97# /logement/<slug>/ (via cache BD) : bloc structuré `.location-data__item`98# (pièces, chambres, salles de bain, chauffage/électricité/internet,99# animaux, fumeur, stationnement, disponibilité), description100# (`.location-more-infos`) et galerie (carrousel Oxygen, liens pleine taille).101# robots.txt WP standard (Disallow /wp-admin/), sitemap XML.102# 2026-09-13 : SiteGround sert son anti-bot sgcaptcha (202 + challenge JS,103# en-tête sg-captcha) aux IP datacenter — invisible du wrapper résilient104# (2xx) ; on bascule alors la session sur un proxy résidentiel Oxylabs CA105# (même pattern que boreal_abitibi/citiluxx/cromwell/deschenes_pepin,106# hébergeur identique).107# -----------------------------------------------------------------------------108from __future__ import annotations109110import hashlib111import os112import re113import time114from urllib.parse import quote115116from bs4 import BeautifulSoup117118from ..schema import Listing, normalize_unit_type, strip_accents119from .base import BaseConnector120121BASE = "https://gestionhabitation.ca"122LIST_URL = f"{BASE}/a-louer/"123124# page interstitielle sgcaptcha SiteGround (meta refresh vers /.well-known/…)125_SG_MARKER = "/.well-known/sgcaptcha/"126127128def _sg_challenge(resp) -> bool:129 """True si la réponse est le challenge anti-bot SiteGround (202 + JS)."""130 if "challenge" in str(resp.headers.get("sg-captcha", "")).lower():131 return True132 return _SG_MARKER in (resp.text or "")[:600]133134# suffixe de redimensionnement WordPress (« -224x300.jpg » -> pleine taille)135_SIZE_SUFFIX = re.compile(r"-\d{2,4}x\d{2,4}(?=\.(?:jpg|jpeg|png|webp)$)", re.I)136# « 3 1/2 », « 3½ », « 4 et demi » dans le titre de la carte137_TYPE_RE = re.compile(r"\b(\d)\s*(?:1/2|½|et\s+demi)", re.I)138139140def _clean_price_label(label: str) -> str:141 """'1,250$/mois' -> '1250$/mois' compatible parse_price (virgule = milliers)."""142 return re.sub(r"(\d),(\d{3})", r"\1\2", label)143144145def _oui_non(raw: str) -> str | None:146 """'Oui'/'Non' du bloc structuré -> 'oui'/'non', sinon None (inconnu)."""147 k = strip_accents((raw or "").strip().lower())148 if k.startswith("oui"):149 return "oui"150 if k.startswith("non"):151 return "non"152 return None153154155class GestionHabitationConnector(BaseConnector):156 source_id = "gestion_habitation"157 request_delay = 0.6158 max_details = 30 # garde-fou fiches détail (vraies requêtes par sync)159160 def _enable_residential_proxy(self) -> bool:161 """Route toute la session via Oxylabs résidentiel CA (session collante)."""162 endpoint = os.environ.get("OXYLABS_PROXY")163 user = os.environ.get("OXYLABS_PROXY_USER")164 pwd = os.environ.get("OXYLABS_PROXY_PASS")165 if not (endpoint and user and pwd):166 return False167 puser = f"{user}-cc-CA-sessid-gesthab{int(time.time())}-sesstime-10"168 proxy = f"http://{quote(puser, safe='')}:{quote(pwd, safe='')}@{endpoint}"169 self.session.proxies = {"http": proxy, "https": proxy}170 self.session.verify = False # CA MITM du proxy Oxylabs (cf. _resilient)171 return True172173 def _get_html(self, url: str) -> str:174 """GET avec contournement du challenge sgcaptcha (proxy résidentiel)."""175 resp = self.get(url)176 if not _sg_challenge(resp):177 return resp.text178 if not self.session.proxies and self._enable_residential_proxy():179 resp = self.get(url)180 if not _sg_challenge(resp):181 return resp.text182 raise RuntimeError(f"challenge sgcaptcha non contourné — {url}")183184 def fetch(self) -> list[Listing]:185 # la page de liste échoue franchement sur challenge (fini le186 # « 0 trouvé ok » silencieux — ingest journalise ok=0)187 html = self._get_html(LIST_URL)188 soup = BeautifulSoup(html, "html.parser")189190 self._fetched = 0191 listings: dict[str, Listing] = {}192 for card in soup.select(".location-card"):193 try:194 self._parse_card(card, listings)195 except Exception:196 continue197 return list(listings.values())198199 # -- carte (.location-card, grille WP Grid Builder rendue serveur) -----------------200 def _parse_card(self, card, listings: dict[str, Listing]) -> None:201 link = card.select_one("a.location-card__permalink[href]")202 if not link:203 return204 url = link["href"]205 m = re.search(r"/logement/([^/?#]+)", url)206 if not m:207 return208 ext_id = m.group(1).strip("/")209 if not ext_id or ext_id in listings:210 return211212 # disponibilité : « DISPONIBLE », « juin 2026 »… — on saute les loués213 avail_el = card.select_one(".location-card__availability")214 availability = avail_el.get_text(" ", strip=True) if avail_el else ""215 if re.search(r"non\s+disponible", availability, re.I):216 return217218 # titre = adresse (ou libellé libre) + n° de porte éventuel219 title_el = link.select_one(".location-card__address .ct-span")220 title = title_el.get_text(strip=True) if title_el else ""221 door_el = link.select_one(".location-card__door .ct-span")222 door = door_el.get_text(strip=True) if door_el else ""223224 # 2e bloc : ville (Val-d'Or, Amos, Malartic) et secteur (Centre-ville…)225 city = sector = ""226 meta_blocks = card.select(".location-card__data-title")227 if len(meta_blocks) > 1:228 spans = meta_blocks[1].select(".ct-span")229 if spans:230 city = spans[0].get_text(strip=True)231 if len(spans) > 1:232 sector = spans[1].get_text(strip=True)233234 # adresse civique seulement si le libellé en est une (commence par un n°)235 address = ""236 if re.match(r"^\d+[\s,]", title):237 address = title + (f", app. {door}" if door else "")238 if city:239 address += f", {city}"240241 price_el = card.select_one(".location-card__price")242 period_el = card.select_one(".location-card__period")243 price_label = ""244 if price_el and price_el.get_text(strip=True):245 price_label = price_el.get_text(strip=True) + \246 (period_el.get_text(strip=True) if period_el else "")247248 img_el = card.select_one("img.location-card__image[src]")249 images = [_SIZE_SUFFIX.sub("", img_el["src"])] if img_el else []250251 # type d'unité : « 3 1/2 » du libellé de la carte (sinon fiche détail)252 unit_type = ""253 m_type = _TYPE_RE.search(title)254 if m_type:255 unit_type = normalize_unit_type(f"{m_type.group(1)} 1/2")256257 lst = Listing(258 source=self.source_id,259 external_id=ext_id,260 url=url,261 title=title + (f" #{door}" if door else ""),262 address=address,263 sector=sector,264 city=city,265 unit_type=unit_type,266 price_label=_clean_price_label(price_label),267 availability=availability,268 images=images,269 )270271 key = hashlib.sha1(272 f"{title}|{price_label}|{availability}|{city}"273 .encode("utf-8")).hexdigest()274 try:275 payload = self.detail(ext_id, key,276 lambda u=url: self._fetch_detail(u))277 self._apply_detail(lst, payload)278 except Exception:279 pass280 listings[ext_id] = lst281282 # -- fiche détail (/logement/<slug>/) ----------------------------------------------283 def _fetch_detail(self, url: str) -> dict:284 """Bloc structuré (pièces, animaux…), description et galerie complète."""285 if self._fetched >= self.max_details:286 raise RuntimeError("budget de fiches détail atteint")287 self._fetched += 1288 # _get_html lève sur challenge : pas de {} vide dans detail_cache289 # (clé figée jamais invalidée)290 html = self._get_html(url)291 soup = BeautifulSoup(html, "html.parser")292 out: dict = {}293294 # paires titre/valeur du bloc .location-data (rendu serveur)295 fields: dict[str, str] = {}296 for it in soup.select(".location-data__item"):297 t_el = it.select_one(".location-data__item-title")298 v_el = it.select_one(".location-data__item-value")299 if not t_el:300 continue301 key = strip_accents(t_el.get_text(strip=True).rstrip(" :").lower())302 val = v_el.get_text(" ", strip=True) if v_el else ""303 if val:304 fields[key] = val305 out["fields"] = fields306307 desc_el = soup.select_one(".location-more-infos")308 if desc_el:309 txt = desc_el.get_text("\n", strip=True)310 txt = re.sub(r"^Sp[ée]cifications\n", "", txt)311 txt = re.sub(r"^Inclusions\n", "", txt)312 out["description"] = re.sub(r"[ \t]+", " ", txt).strip()[:1500]313314 images: list[str] = []315 for a in soup.select("a.oxy-carousel-builder_gallery-image[href]"):316 u = a["href"].strip()317 if u.startswith("http") and u not in images:318 images.append(u)319 out["images"] = images[:25]320 return out321322 def _apply_detail(self, lst: Listing, d: dict) -> None:323 """Reporte le payload (frais ou en cache) sur l'annonce."""324 if not d:325 return326 if d.get("description"):327 lst.description = d["description"]328 if d.get("images") and len(d["images"]) > len(lst.images):329 lst.images = d["images"]330331 fields = d.get("fields") or {}332 amenities: list[str] = []333 pieces = fields.get("nombre de pieces", "")334 if pieces.isdigit():335 amenities.append(f"{pieces} pièce(s)")336 # le site affiche « n½ » pour n pièces : dérivation fidèle337 if not lst.unit_type:338 lst.unit_type = normalize_unit_type(f"{pieces} 1/2")339 if fields.get("chambre(s)"):340 amenities.append(f"{fields['chambre(s)']} chambre(s)")341 if fields.get("salle de bain(s)"):342 amenities.append(f"{fields['salle de bain(s)']} salle(s) de bain")343 for label, key in (("Chauffage", "chauffage"),344 ("Électricité", "electricite"),345 ("Internet", "internet"),346 ("Stationnement", "stationnement")):347 if fields.get(key):348 amenities.append(f"{label} : {fields[key]}")349 if fields.get("fumeur"):350 amenities.append(f"Fumeur : {fields['fumeur']}")351 lst.amenities = list(dict.fromkeys(lst.amenities + amenities))352353 lst.pets = _oui_non(fields.get("animaux", ""))354 if not lst.availability and fields.get("disponibilite"):355 lst.availability = fields["disponibilite"]356 if not lst.price_label and fields.get("prix"):357 lst.price_label = _clean_price_label(fields["prix"])358 if not lst.city and fields.get("ville"):359 lst.city = fields["ville"]360 if not lst.sector and fields.get("secteur"):361 lst.sector = fields["secteur"]362