Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/boreal_abitibi.py10# Module : louka11# Repository : https://git.spboucher.ai/lou-ka12# Created : 2026-08-0913# Last Modified : 2026-09-1414#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/boreal_abitibi.py : connecteur Constructions Boréal Abitibi91# (constructionsborealabitibi.com — Val-d'Or et Malartic, logements neufs ;92# seul acteur structuré à Malartic). WordPress + thème maison Tailwind : la93# grille /locations/ est remplie en AJAX (admin-ajax.php, action=get_rents,94# nonce lu dans le HTML de la page). Chaque « rent » est une carte HTML95# `article.listing-item` : ville (Val-d'Or/Malartic), adresse + n° d'app.,96# prix (« 1 550 $ / mois »), « Disponible en août », chambres/salles de97# bain/garage (pictos), « Non meublé, non chauffé, non éclairé ». Fiche98# détail /loyer/<slug>/ (via cache BD) : Grandeur (4 et demi), étage,99# parking, inclusions, description et galerie ; la mention « logements100# non-fumeur / aucun animal » du site alimente `pets`.101# robots.txt WP standard (admin-ajax.php explicitement permis), 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# en session collante (le nonce et les POST admin-ajax partagent l'IP).106# 2026-09-14 : le challenge frappe aussi les IP résidentielles (~1 run sur 2)107# et parfois le POST admin-ajax seul (réponse HTML 202 → .json() lève) ;108# on tourne donc l'IP collante (2 essais) et on relance le POST une fois109# avec nouvelle IP + nouveau nonce avant l'erreur franche.110# -----------------------------------------------------------------------------111from __future__ import annotations112113import hashlib114import json115import os116import re117import time118from urllib.parse import quote119120from bs4 import BeautifulSoup121122from ..schema import Listing, normalize_unit_type, parse_price123from .base import BaseConnector124125BASE = "https://constructionsborealabitibi.com"126LIST_URL = f"{BASE}/locations/"127AJAX_URL = f"{BASE}/wp-admin/admin-ajax.php"128129# suffixe de redimensionnement WordPress (« -512x384.jpg » -> pleine taille)130_SIZE_SUFFIX = re.compile(r"-\d{2,4}x\d{2,4}(?=\.(?:jpg|jpeg|png|webp)$)", re.I)131_AJAX_OBJECT_RE = re.compile(r"var ajax_object\s*=\s*(\{.*?\})\s*;?", re.S)132# « 4 et demi » (fiche) -> « 4 1/2 » pour la normalisation commune133_ET_DEMI_RE = re.compile(r"^(\d)\s*et\s*demi$", re.I)134# page interstitielle sgcaptcha SiteGround (meta refresh vers /.well-known/…)135_SG_MARKER = "/.well-known/sgcaptcha/"136137138def _sg_challenge(resp) -> bool:139 """True si la réponse est le challenge anti-bot SiteGround (202 + JS)."""140 if "challenge" in str(resp.headers.get("sg-captcha", "")).lower():141 return True142 return _SG_MARKER in (resp.text or "")[:600]143144145class BorealAbitibiConnector(BaseConnector):146 source_id = "boreal_abitibi"147 request_delay = 0.6148 max_details = 30 # garde-fou fiches détail (vraies requêtes par sync)149 max_pages = 10 # garde-fou pagination AJAX150151 def _post(self, url: str, data: dict):152 """POST avec le même throttling poli que get()."""153 wait = self.request_delay - (time.time() - self._last_request)154 if wait > 0:155 time.sleep(wait)156 resp = self.session.post(url, data=data, timeout=self.timeout)157 self._last_request = time.time()158 resp.raise_for_status()159 return resp160161 def _enable_residential_proxy(self) -> bool:162 """Route toute la session via Oxylabs résidentiel CA (session collante)."""163 endpoint = os.environ.get("OXYLABS_PROXY")164 user = os.environ.get("OXYLABS_PROXY_USER")165 pwd = os.environ.get("OXYLABS_PROXY_PASS")166 if not (endpoint and user and pwd):167 return False168 puser = f"{user}-cc-CA-sessid-boreal{time.time_ns()}-sesstime-10"169 proxy = f"http://{quote(puser, safe='')}:{quote(pwd, safe='')}@{endpoint}"170 self.session.proxies = {"http": proxy, "https": proxy}171 self.session.verify = False # CA MITM du proxy Oxylabs (cf. _resilient)172 return True173174 def _get_html(self, url: str) -> str:175 """GET avec contournement du challenge sgcaptcha (proxy résidentiel).176177 Une IP résidentielle collante peut elle-même être flaguée : on tire178 jusqu'à 2 nouvelles sessions collantes avant l'erreur franche.179 """180 resp = self.get(url)181 if not _sg_challenge(resp):182 return resp.text183 for _ in range(2):184 if not self._enable_residential_proxy():185 break186 resp = self.get(url)187 if not _sg_challenge(resp):188 return resp.text189 raise RuntimeError(f"challenge sgcaptcha non contourné — {url}")190191 def _nonce(self) -> str:192 """Nonce AJAX lu dans le HTML de /locations/ (grille vide côté serveur)."""193 html = self._get_html(LIST_URL)194 m = _AJAX_OBJECT_RE.search(html)195 if not m:196 raise RuntimeError("ajax_object introuvable sur /locations/")197 return json.loads(m.group(1)).get("nonce", "")198199 def _get_rents(self, nonce: str, page: int) -> dict:200 """Une page admin-ajax get_rents ; RuntimeError si challenge sgcaptcha."""201 resp = self._post(AJAX_URL, {202 "action": "get_rents", "nonce": nonce, "page": str(page),203 "posts_per_page": "12", "town": "", "show_all": "",204 })205 if _sg_challenge(resp):206 raise RuntimeError("challenge sgcaptcha sur admin-ajax get_rents")207 try:208 return resp.json()209 except ValueError as exc: # challenge servi sans en-tête sg-captcha210 raise RuntimeError(f"réponse non-JSON d'admin-ajax get_rents: {exc}")211212 def fetch(self) -> list[Listing]:213 # 1) nonce AJAX, puis 2) admin-ajax get_rents paginé (toutes villes)214 nonce = self._nonce()215 self._fetched = 0216 listings: dict[str, Listing] = {}217 page = 1218 retried = False219 while page <= self.max_pages:220 try:221 payload = self._get_rents(nonce, page)222 except RuntimeError:223 if retried:224 raise225 retried = True226 # IP flaguée en cours de route : nouvelle IP collante + nonce227 self._enable_residential_proxy()228 nonce = self._nonce()229 continue230 for card_html in payload.get("rents") or []:231 try:232 self._parse_card(BeautifulSoup(card_html, "html.parser"),233 listings)234 except Exception:235 continue236 if page >= int(payload.get("max_num_pages") or 1):237 break238 page += 1239 return list(listings.values())240241 # -- carte (article.listing-item retournée par get_rents) ---------------------------242 def _parse_card(self, card, listings: dict[str, Listing]) -> None:243 link = card.select_one('a[href*="/loyer/"]')244 if not link:245 return246 url = link["href"].strip()247 m = re.search(r"/loyer/([^/?#]+)", url)248 if not m:249 return250 ext_id = m.group(1).strip("/")251 if not ext_id or ext_id in listings:252 return253254 # ville (« Val-d'Or », « Malartic ») + adresse et n° d'appartement255 city_el = card.select_one("div.h4 strong")256 city = city_el.get_text(strip=True) if city_el else ""257 title_el = card.select_one("h3 a")258 title = re.sub(r"\s+", " ",259 title_el.get_text(" ", strip=True)) if title_el else ""260 address = f"{title}, {city}" if title and city else title261262 # rangée prix / disponibilité : « 1 550 $ / mois » | « Disponible en août »263 price_label = availability = ""264 for div in card.select("div"):265 txt = re.sub(r"\s+", " ", div.get_text(" ", strip=True))266 if not div.find("div") and re.match(r"^\d[\d\s]*\$\s*/\s*mois$", txt, re.I):267 price_label = txt268 elif not div.find("div") and re.match(r"^Disponible", txt, re.I):269 availability = txt270271 # pictos : chambres / salles de bain / garage272 amenities: list[str] = []273 for icon, label in (("icon-bedroom", "chambre(s)"),274 ("icon-bathroom", "salle(s) de bain"),275 ("icon-garage", "garage/stationnement")):276 ic = card.select_one(f"span.{icon}")277 if ic:278 val = ic.find_next_sibling("span")279 if val and val.get_text(strip=True):280 amenities.append(f"{val.get_text(strip=True)} {label}")281 # mention « Non meublé, non chauffé, non éclairé »282 for div in card.select("div.self-end"):283 txt = div.get_text(" ", strip=True)284 if txt:285 amenities.append(txt)286287 # photo de couverture (le lazy-load expose data-srcset avec la pleine taille)288 images: list[str] = []289 img = card.select_one("img[data-srcset], img[data-src], img[src]")290 if img:291 srcset = img.get("data-srcset") or ""292 candidates = re.findall(r"(https?://\S+)\s+(\d+)w", srcset)293 if candidates:294 images.append(max(candidates, key=lambda c: int(c[1]))[0])295 else:296 u = img.get("data-src") or img.get("src") or ""297 if u.startswith("http"):298 images.append(_SIZE_SUFFIX.sub("", u))299300 lst = Listing(301 source=self.source_id,302 external_id=ext_id,303 url=url,304 title=f"{title} — {city}".strip(" —"),305 address=address,306 city=city,307 price=parse_price(price_label),308 price_label=price_label,309 availability=availability,310 amenities=amenities,311 images=images,312 )313314 key = hashlib.sha1(315 f"{title}|{price_label}|{availability}|{city}"316 .encode("utf-8")).hexdigest()317 try:318 payload = self.detail(ext_id, key,319 lambda u=url: self._fetch_detail(u))320 self._apply_detail(lst, payload)321 except Exception:322 pass323 listings[ext_id] = lst324325 # -- fiche détail (/loyer/<slug>/) ---------------------------------------------------326 def _fetch_detail(self, url: str) -> dict:327 """Grandeur, étage, parking, inclusions, description, galerie, animaux."""328 if self._fetched >= self.max_details:329 raise RuntimeError("budget de fiches détail atteint")330 self._fetched += 1331 # lever sur challenge : sinon detail() mettrait en cache un payload vide332 html = self._get_html(url)333 soup = BeautifulSoup(html, "html.parser")334 out: dict = {}335336 # tableau de specs : rangées h2 (libellé) / div (valeur)337 fields: dict[str, str] = {}338 for row in soup.find_all("div", class_="lg:table-row"):339 h2 = row.find("h2")340 val = row.find("div")341 if h2 and val:342 fields[h2.get_text(strip=True).lower()] = \343 re.sub(r"\s+", " ", val.get_text(" ", strip=True))344 out["fields"] = fields345346 # description : bloc texte libre (proximité écoles/épiceries…)347 desc = ""348 for div in soup.select("div.p-10"):349 txt = div.get_text("\n", strip=True)350 if re.search(r"proximit[ée]", txt, re.I) and len(txt) > len(desc):351 desc = txt352 if desc:353 out["description"] = re.sub(r"[ \t]+", " ", desc).strip()[:1500]354355 # mention transversale affichée sur chaque fiche356 if re.search(r"N[’']ACCEPTONS\s+PAS\s+LES\s+ANIMAUX",357 soup.get_text(" ", strip=True), re.I):358 out["pets"] = "non"359360 # galerie : images lazy-load (lozad) -> data-src, pleine taille361 images: list[str] = []362 for img in soup.select('img[data-src*="/wp-content/uploads/"], '363 'img[src*="/wp-content/uploads/"]'):364 u = _SIZE_SUFFIX.sub("", img.get("data-src") or img.get("src") or "")365 if u.startswith("http") and u not in images:366 images.append(u)367 out["images"] = images[:25]368 return out369370 def _apply_detail(self, lst: Listing, d: dict) -> None:371 """Reporte le payload (frais ou en cache) sur l'annonce."""372 if not d:373 return374 fields = d.get("fields") or {}375 grandeur = fields.get("grandeur", "")376 m = _ET_DEMI_RE.match(grandeur)377 if m:378 lst.unit_type = normalize_unit_type(f"{m.group(1)} 1/2")379 elif grandeur:380 lst.unit_type = normalize_unit_type(grandeur)381382 extra: list[str] = []383 if fields.get("étage") or fields.get("etage"):384 extra.append(f"Étage : {fields.get('étage') or fields.get('etage')}")385 if fields.get("parking"):386 extra.append(f"Stationnement : {fields['parking']}")387 if fields.get("inclusions"):388 extra.append(f"Inclus : {fields['inclusions']}")389 if extra:390 lst.amenities = list(dict.fromkeys(lst.amenities + extra))391392 if not lst.availability and fields.get("disponible"):393 lst.availability = f"Disponible {fields['disponible']}"394 if d.get("description"):395 lst.description = d["description"]396 if d.get("pets"):397 lst.pets = d["pets"]398 if d.get("images") and len(d["images"]) > len(lst.images):399 lst.images = d["images"]400