Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/bons_locataires.py10# Module : louka11# Repository : https://git.spboucher.ai/lou-ka12# Created : 2026-08-1713# Last Modified : 2026-08-1714#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/bons_locataires.py : Bons Locataires (bonslocataires.com) — agence91# de location Montréal/Laval/Longueuil. WordPress, aucun anti-bot (seul92# mod_security bloque les sitemaps XML — on ne les utilise pas).93# Source de vérité : la page carte MapListPro (~8 Mo) dont le tableau JSON94# inline contient les 1 600+ emplacements avec lat/lng, taxonomies95# (région/quartier/taille) et description complète. Le site garde les96# logements loués sur la carte (« DÉJÀ LOUÉ », pin PouceVert) : on ne97# conserve que les annonces encore offertes, et on valide que leur page98# (locationUrl) répond toujours 200 (certains vieux liens sont morts).99# Prix et disponibilité en texte libre -> regex. ~20-40 annonces actives.100# -----------------------------------------------------------------------------101from __future__ import annotations102103import html as H104import json105import re106107from ..schema import Listing, normalize_unit_type108from .base import BaseConnector109110MAP_PAGE = ("https://www.bonslocataires.com/logement-appartement-a-louer-"111 "enquete-proprio-credit-locataire-visite-virtuelle-360/")112113_PRICE_RE = re.compile(r"(\d{3,4})\s*\$\s*(?:/|par)?\s*mois", re.I)114_PRICE_ALT_RE = re.compile(r"(\d{3,4})\s*\$")115_IMG_RE = re.compile(r'src="(https?://www\.bonslocataires\.com/wp-content/'116 r'uploads/[^"]+)"')117_LOC_ID_RE = re.compile(r"loc-(\d+)")118_TAG_RE = re.compile(r"<[^>]+>")119120121def _texte(fragment: str) -> str:122 return re.sub(r"\s+\n", "\n", H.unescape(_TAG_RE.sub("", fragment or ""))).strip()123124125class BonsLocatairesConnector(BaseConnector):126 source_id = "bons_locataires"127 request_delay = 1.0128 timeout = 120 # la page carte fait ~8 Mo129130 def _map_objects(self) -> list[dict]:131 import time132 html = ""133 for attempt in range(3): # mod_security coupe parfois la page 8 Mo134 try:135 html = self.get(MAP_PAGE).text136 break137 except Exception:138 if attempt == 2:139 raise140 time.sleep(20 * (attempt + 1))141 i = html.find('[{"title":')142 if i < 0:143 return []144 depth, end = 0, None145 for j in range(i, len(html)):146 if html[j] == "[":147 depth += 1148 elif html[j] == "]":149 depth -= 1150 if depth == 0:151 end = j + 1152 break153 try:154 return json.loads(html[i:end])155 except ValueError:156 return []157158 @staticmethod159 def _available(obj: dict) -> bool:160 blob = (obj.get("title", "") + (obj.get("description") or "")161 + (obj.get("icon") or "") + (obj.get("pinImageUrl") or ""))162 return "LOU" not in blob.upper() or "PouceVert" not in blob163164 def fetch(self) -> list[Listing]:165 out: list[Listing] = []166 for obj in self._map_objects():167 desc_html = obj.get("description") or ""168 blob = (obj.get("title", "") + desc_html).upper()169 pin = (obj.get("pinImageUrl") or "") + (obj.get("icon") or "")170 if "DÉJÀ LOU" in blob or "DEJA LOU" in blob or "LOUÉ!" in blob \171 or "PouceVert" in pin:172 continue173 url = (obj.get("locationUrl") or "").replace("http://", "https://")174 if not url:175 continue176 try: # vieux liens morts -> annonce écartée177 page_html = self.get(url).text178 except Exception:179 continue180 m = _LOC_ID_RE.search(obj.get("cssClass") or "")181 eid = m.group(1) if m else url.rstrip("/").rsplit("/", 1)[-1]182183 cats = obj.get("customCategories") or {}184 def _first(tax: str) -> str:185 terms = cats.get(tax) or []186 return terms[0].get("name", "") if terms else ""187 city = _first("map_location_categories_region") or "Montréal"188 sector = _first("map_location_categories_city")189 taille = _first("map_location_categories_taille")190191 title = _texte(obj.get("title", "")).strip("* ")192 unit_type = normalize_unit_type(taille or title)193 if not re.match(r"^\d½$|^6½\+$|^Studio$|^Loft$|^Chambre", unit_type or ""):194 unit_type = ""195196 # la fiche WordPress (déjà téléchargée pour la validation) est plus197 # riche que le popup carte : prix, galerie, disponibilité198 page_main = ""199 m = re.search(r'<div class="entry-content[^"]*">(.*?)</div>\s*'200 r'(?:<footer|<div class="entry-footer)', page_html, re.S)201 if not m:202 m = re.search(r"<article\b.*?</article>", page_html, re.S)203 if m:204 page_main = m.group(0)205 page_text = _texte(page_main)206207 description = _texte(desc_html)208 if 100 < len(page_text) and len(page_text) > len(description):209 description = page_text210 price = None # le popup carte prime : texte ciblé211 for texte in (_texte(desc_html), page_text):212 m = _PRICE_RE.search(texte) or _PRICE_ALT_RE.search(texte)213 if m and 400 <= float(m.group(1)) <= 5000:214 price = float(m.group(1))215 break216 availability = ""217 m = re.search(r"[Dd]isponible[^.\n<]{0,70}", description)218 if m:219 availability = m.group(0).strip()220 images = []221 for u in _IMG_RE.findall(page_main) + _IMG_RE.findall(desc_html):222 u = u.replace("http://", "https://")223 if u not in images:224 images.append(u)225 try:226 lat, lng = float(obj.get("latitude")), float(obj.get("longitude"))227 except (TypeError, ValueError):228 lat = lng = None229 out.append(Listing(230 source=self.source_id,231 external_id=str(eid),232 url=url,233 title=title,234 sector=sector,235 city=city,236 unit_type=unit_type,237 price=price,238 price_label=(f"{price:,.0f} $/mois".replace(",", " ")239 if price else ""),240 availability=availability,241 description=description[:6000],242 images=images,243 lat=lat,244 lng=lng,245 ))246 return out247