Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/alouer_sherbrooke.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/alouer_sherbrooke.py : connecteur À Louer Sherbrooke91# (alouersherbrooke.com) — 100+ logements dans 5 immeubles regroupés du92# quartier Université (Sherbrooke) ; clientèle étudiants/professionnels/93# retraités. WordPress (thème idconception) : la liste est servie par94# admin-ajax `pagination-load-posts` (CPT appartements, 8 cartes/page,95# pagination dans la réponse). Cartes : classe `dispo` (À louer, avec date96# « À partir du … ») ou `loue` (Loué — exclues), grandeur (3½…), quartier,97# inclusions et photo. Les fiches (via self.detail, cache BD) ajoutent la98# description complète et la galerie. AUCUN prix ni adresse civique publiés99# par la source (immeubles regroupés, quartier Université) — champs laissés100# vides, rien d'inventé. external_id = slug du billet.101# -----------------------------------------------------------------------------102from __future__ import annotations103104import hashlib105import re106107from bs4 import BeautifulSoup108109from ..schema import Listing, normalize_unit_type110from .base import BaseConnector111112BASE = "https://www.alouersherbrooke.com"113AJAX_URL = f"{BASE}/wp-admin/admin-ajax.php"114115_VARIANT_IMG = re.compile(r"-\d{2,4}x\d{2,4}(?=\.(?:jpg|jpeg|png|webp)$)", re.I)116117118class AlouerSherbrookeConnector(BaseConnector):119 source_id = "alouer_sherbrooke"120 request_delay = 0.6121 max_pages = 12 # garde-fou (7 pages observées)122 max_details = 30 # garde-fou fiches détail (vraies requêtes)123124 def _ajax_page(self, page: int) -> BeautifulSoup:125 resp = self.session.post(126 AJAX_URL,127 data={"page": str(page), "action": "pagination-load-posts"},128 timeout=self.timeout)129 resp.raise_for_status()130 return BeautifulSoup(resp.text, "html.parser")131132 def fetch(self) -> list[Listing]:133 listings: dict[str, Listing] = {}134 for page in range(1, self.max_pages + 1):135 try:136 soup = self._ajax_page(page)137 except Exception:138 break139 cards = soup.select(".appartements__bloc")140 if not cards:141 break142 for card in cards:143 try:144 lst = self._parse_card(card)145 except Exception:146 continue147 if lst and lst.external_id not in listings:148 listings[lst.external_id] = lst149 # borne réelle de pagination (liens numériques de la réponse)150 nums = [int(a.get_text(strip=True))151 for a in soup.select(".cvf-universal-pagination li a")152 if a.get_text(strip=True).isdigit()]153 if nums and page >= max(nums):154 break155156 # fiches détail (cache BD) : description + galerie157 self._fetched = 0158 for lst in listings.values():159 key = hashlib.sha1(160 f"{lst.title}|{lst.availability}|{lst.unit_type}"161 .encode("utf-8")).hexdigest()162 try:163 payload = self.detail(lst.external_id, key,164 lambda u=lst.url: self._fetch_detail(u))165 except Exception:166 continue167 if payload.get("description"):168 lst.description = payload["description"]169 if payload.get("images"):170 lst.images = list(dict.fromkeys(payload["images"] + lst.images))[:20]171 return list(listings.values())172173 # -- carte AJAX -------------------------------------------------------------174 def _parse_card(self, card) -> Listing | None:175 classes = card.get("class") or []176 if "dispo" not in classes:177 return None # « loue » = logement loué, exclu178 link = card.select_one("a[href*='/appartements/']")179 if not link:180 return None181 url = link["href"].split("?")[0]182 m = re.search(r"/appartements/([^/]+)/?$", url.rstrip("/") + "/")183 m = re.search(r"/appartements/([^/]+)", url)184 if not m:185 return None186 slug = m.group(1).strip("/")187188 title = (link.get("title") or "").strip()189 if not title:190 h2 = card.select_one("h2")191 title = h2.get_text(" ", strip=True) if h2 else slug.replace("-", " ")192193 # « À louer » + « À partir du 1 septembre 2026 »194 tag = card.select_one(".appartements__dispoTag")195 date = card.select_one(".appartements__date")196 availability = " ".join(x for x in (197 tag.get_text(" ", strip=True) if tag else "",198 date.get_text(" ", strip=True) if date else "") if x).strip()199200 gr = card.select_one(".appartement__grandeur")201 unit_type = normalize_unit_type(gr.get_text(strip=True) if gr else "")202 if not re.fullmatch(r"\d½\+?|6½\+|Studio|Loft|Chambre|Maison",203 unit_type or ""):204 unit_type = ""205206 qu = card.select_one(".appartement__quartier")207 sector = re.sub(r"\s+", " ",208 qu.get_text(" ", strip=True)).strip() if qu else ""209210 amenities = []211 for li in card.select("li"):212 t = re.sub(r"\s+", " ", li.get_text(" ", strip=True))213 if t and t not in amenities:214 amenities.append(t)215216 img = card.select_one("img[src]")217 images = []218 if img and str(img.get("src", "")).startswith("http"):219 images.append(_VARIANT_IMG.sub("", img["src"]))220221 return Listing(222 source=self.source_id,223 external_id=slug,224 url=url,225 title=title,226 address="", # adresse civique non publiée par la source227 sector=sector, # « Université »228 city="Sherbrooke",229 unit_type=unit_type,230 availability=availability,231 amenities=amenities,232 images=images,233 )234235 # -- fiche appartement --------------------------------------------------------236 def _fetch_detail(self, url: str) -> dict:237 if self._fetched >= self.max_details:238 raise RuntimeError("budget de fiches détail atteint")239 self._fetched += 1240 html = self.get(url).text241 soup = BeautifulSoup(html, "html.parser")242 out: dict = {}243244 # contenu du billet : listes descriptives (appartement, immeuble, à245 # proximité) — tout en texte brut, le textmine central s'en charge246 main = soup.select_one("article, .single__content, main") or soup247 parts: list[str] = []248 for el in main.find_all(["p", "li", "h2", "h3"]):249 t = re.sub(r"\s+", " ", el.get_text(" ", strip=True)).strip()250 if t and t not in parts:251 parts.append(t)252 if sum(len(x) for x in parts) > 1500:253 break254 if parts:255 out["description"] = " | ".join(parts)[:1500]256257 images = []258 for img in soup.select("img[src*='/wp-content/uploads/']"):259 src = _VARIANT_IMG.sub("", str(img.get("src") or ""))260 if src.startswith("http") and src not in images \261 and not re.search(r"logo|icon|favicon", src, re.I):262 images.append(src)263 out["images"] = images[:20]264 return out265