Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Immo·Ka9# File : immoka/connectors/kw_distinction.py10# Module : immoka11# Repository : https://git.spboucher.ai/immo-ka12# Created : 2026-08-1213# Last Modified : 2026-08-2314#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# Immo-Ka — Agrégateur de maisons à vendre (province de Québec)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# connectors/kw_distinction.py : Keller Williams Distinction (Gatineau/Outaouais)91# Site ASP.NET (plateforme Olivex/tonikweb). La page « Trouver une propriété »92# est rendue serveur et paginée par querystring (PageID=1..N, ~6 cartes/page,93# total affiché « N résultat(s) ») : cartes complètes — type, prix, adresse,94# ville (secteur), MLS, cac/sdb, résumé, photo. Les fiches détail sont aussi95# rendues serveur : galerie complète (/_upload/photos/{id}-{n}.jpg),96# description, tableau « Détails de la propriété », proximité.97# ⚠️ Ne PAS revenir au sitemap.xml : il est figé (anciennes URL98# « sector--city » qui redirigent toutes vers /Pages/Erreur/) — c'est ce qui99# avait laissé la source à 0 % prix/photos/description.100# ⚠️ 2026-08-23 : double panne côté site — (1) cert TLS expiré (Let's Encrypt101# non renouvelé) → SSLError sur toute requête directe ; (2) la recherche102# globale (/Pages/Listings/Default.aspx) répond 500 → redirect /Pages/500/.103# Parades : session en verify=False, et si la recherche donne 0 carte, repli104# sur les pages courtier (même markup listing_bloc, module distinct qui105# fonctionne) énumérées depuis l'annuaire des courtiers.106# -----------------------------------------------------------------------------107from __future__ import annotations108109import html as _html110import os111import re112113import requests114import urllib3115116from .base import BaseConnector117from . import _detailutil as du118from ..normalize import parse_price, parse_year119from ..schema import PropertyListing120121BASE = "https://www.kwdistinction.com"122QS = ("?intMunicipaliteId=&intTypeHabitation=&curPrixFrom=0&curPrixTo=999999999"123 "&PageID={page}&intListeMode=1&intSecteur=&intTri=2")124LIST = BASE + "/maison-a-vendre-au-quebec/condo-a-vendre-au-quebec/" + QS125COURTIERS = (BASE + "/agence-immobiliere-au-quebec/courtier-immobilier-quebec/"126 "courtier-immobilier-hull")127DETAIL_LIMIT = int(os.environ.get("IMMOKA_KW_DETAIL_LIMIT", "400"))128129_BROKER_RE = re.compile(130 r'href="(/courtier-immobilier-quebec/courtier-immobilier-hull/[^"?#]+)')131132_TOTAL_RE = re.compile(r"(\d+)\s*r[ée]sultat", re.I)133_HREF_RE = re.compile(r'href="(/maisons?-a-vendre-[^"]+/(\d{6,}))"')134_TITLE_RE = re.compile(r'class="listing_text_title"[^>]*>(.*?)</p>', re.S)135_PRICE_RE = re.compile(r'class="listing_text_price"[^>]*>(.*?)</p>', re.S)136_ADDR_RE = re.compile(r'class="listing_text_adresse"[^>]*>(.*?)</p>', re.S)137_ROOMS_RE = re.compile(r'class="listing_text_room"[^>]*>(.*?)</p>', re.S)138_DESC_RE = re.compile(r'class="listing_text_description"[^>]*>(.*?)</p>', re.S)139_BED_RE = re.compile(r"Chambres?\s*:\s*(\d+)")140_BATH_RE = re.compile(r"Salles? de bains?\s*:\s*(\d+)")141142# fiche détail143_PHOTO_RE = re.compile(r'/_upload/photos/(\d{6,})-(\d+)\.jpg', re.I)144_DDESC_RE = re.compile(145 r'titre_texte_fiche_propriete">\s*Description\s*</p>\s*<p[^>]*>(.*?)</p>',146 re.S)147_PROX_RE = re.compile(148 r'titre_texte_fiche_propriete">\s*Proximité\s*</p>\s*<p[^>]*>(.*?)</p>', re.S)149_ROW_RE = re.compile(150 r'<td class="ProprieteInfoText">\s*(.*?)\s*</td>\s*<td[^>]*>\s*(.*?)\s*</td>',151 re.S)152153154def _txt(s: str) -> str:155 return _html.unescape(re.sub(r"<[^>]+>", " ", s or "")).replace("\xa0", " ").strip()156157158def _city_sector(label: str) -> tuple[str, str]:159 """« Gatineau (Hull) » -> (Gatineau, Hull) ; « Bouchette » -> (Bouchette, '')."""160 m = re.match(r"(.+?)\s*\((.+?)\)\s*$", label or "")161 if m:162 return m.group(1).strip(), m.group(2).strip()163 return (label or "").strip(), ""164165166class KwDistinctionConnector(BaseConnector):167 source_id = "kw_distinction"168 request_delay = 0.5169170 def __init__(self) -> None:171 super().__init__()172 # cert TLS du site expiré le 2026-08-23 (Let's Encrypt non renouvelé) :173 # sans verify=False, chaque requête directe lève SSLError et la source174 # tombe à 0 (l'escalade payante finissait sur un 200 vide).175 self.session.verify = False176 urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)177178 def fetch(self) -> list[PropertyListing]:179 by_id: dict[str, PropertyListing] = {}180 try:181 self._scan(LIST, by_id, read_total=True)182 except requests.RequestException:183 pass184 if not by_id:185 # recherche globale en panne (500 serveur, vu 2026-08-23) : repli186 # sur les pages courtier — même cartes listing_bloc, module qui187 # fonctionne ; la dédup par external_id absorbe les co-inscriptions.188 for path in self._broker_paths():189 try:190 self._scan(BASE + path + QS, by_id)191 except requests.RequestException:192 continue193 listings = list(by_id.values())194 du.enrich(self, listings, DETAIL_LIMIT, parse_kw_distinction_detail, key="v2")195 return listings196197 def _scan(self, url_tmpl: str, by_id: dict[str, PropertyListing],198 read_total: bool = False) -> None:199 """Pagine une liste (PageID=1..N) et accumule les cartes dans by_id.200201 La fin de pagination est détectée sur les ids vus DANS CE PARCOURS202 (`local`) : une page courtier pleine de co-inscriptions déjà connues203 d'un confrère ne doit pas stopper le parcours de ses propres pages."""204 total = None205 local: set[str] = set()206 page = 1207 while page <= 80: # garde-fou (~6 cartes/page)208 html = self.get(url_tmpl.format(page=page)).text209 if read_total and total is None:210 m = _TOTAL_RE.search(html)211 total = int(m.group(1)) if m else None212 new = 0213 for bloc in html.split('class="listing_bloc"')[1:]:214 bloc = bloc[:5000] # ne pas déborder sur le pied de page215 lst = self._to_listing(bloc)216 if lst is None:217 continue218 if lst.external_id not in local:219 local.add(lst.external_id)220 new += 1221 if lst.external_id not in by_id:222 by_id[lst.external_id] = lst223 if new == 0 or (total and len(local) >= total):224 break225 page += 1226227 def _broker_paths(self) -> list[str]:228 html = self.get(COURTIERS).text229 seen: dict[str, None] = {}230 for path in _BROKER_RE.findall(html):231 seen.setdefault(path)232 return list(seen)233234 def _to_listing(self, bloc: str) -> PropertyListing | None:235 m = _HREF_RE.search(bloc)236 if not m:237 return None238 path, cid = m.group(1), m.group(2)239 m_title = _TITLE_RE.search(bloc)240 m_price = _PRICE_RE.search(bloc)241 m_addr = _ADDR_RE.search(bloc)242 m_rooms = _ROOMS_RE.search(bloc)243 m_desc = _DESC_RE.search(bloc)244 address = cityline = ""245 if m_addr:246 parts = re.split(r"<br\s*/?>", m_addr.group(1))247 address = _txt(parts[0])248 cityline = _txt(parts[1]) if len(parts) > 1 else ""249 city, sector = _city_sector(cityline)250 rooms = m_rooms.group(1) if m_rooms else ""251 beds = _BED_RE.search(rooms)252 baths = _BATH_RE.search(rooms)253 price_label = _txt(m_price.group(1)) if m_price else ""254 ptype = _txt(m_title.group(1)) if m_title else ""255 low = price_label.lower()256 status = "vendu" if low.startswith(("vendu", "loué", "loue")) else "a-vendre"257 return PropertyListing(258 source=self.source_id,259 external_id=cid,260 url=BASE + path,261 title=address or ptype,262 status=status,263 address=address,264 city=city,265 sector=sector,266 property_type=ptype,267 price=parse_price(price_label),268 price_label=price_label,269 bedrooms=int(beds.group(1)) if beds else None,270 bathrooms=int(baths.group(1)) if baths else None,271 description=_txt(m_desc.group(1)).rstrip(" .") if m_desc else "",272 images=[f"{BASE}/_upload/photos/{cid}-1.jpg"],273 mls=cid,274 broker_name="Keller Williams Distinction",275 agency="Keller Williams Distinction",276 )277278279def parse_kw_distinction_detail(html: str) -> dict:280 """Fiche détail Olivex : galerie complète, description, tableau « Détails281 de la propriété » (chambres, sdb, année, superficies…), proximité."""282 out: dict = {}283 # galerie : la page contient aussi la photo -1 d'autres inscriptions (menu) ;284 # la fiche courante est le seul id avec des numéros de photo > 1285 by_id: dict[str, set[int]] = {}286 for pid, n in _PHOTO_RE.findall(html):287 by_id.setdefault(pid, set()).add(int(n))288 cur = max(by_id, key=lambda p: len(by_id[p]), default=None)289 if cur and len(by_id[cur]) > 1:290 out["images"] = [f"{BASE}/_upload/photos/{cur}-{n}.jpg"291 for n in sorted(by_id[cur])]292 m = _DDESC_RE.search(html)293 if m:294 d = _txt(m.group(1))295 if len(d) > 40:296 out["description"] = d297 m = _PROX_RE.search(html)298 if m:299 feats = [f.strip() for f in _txt(m.group(1)).split(",") if f.strip()]300 if feats:301 out["features"] = feats302 details: dict = {}303 for lab, val in _ROW_RE.findall(html):304 lab = _txt(lab).rstrip(" :")305 val = _txt(val)306 if lab and val and len(val) <= 300:307 details[lab] = val308 if details:309 def dget(pattern: str):310 return next((v for k, v in details.items()311 if re.match(pattern, k, re.I)), None)312 # promotion vers les colonnes structurées313 if dget(r"Chambres à coucher"):314 out["bedrooms"] = du._int(dget(r"Chambres à coucher"))315 if dget(r"Salles? de bains?"):316 out["bathrooms"] = du._int(dget(r"Salles? de bains?"))317 if dget(r"Salles? d.eau"):318 out["powder_rooms"] = du._int(dget(r"Salles? d.eau"))319 y = parse_year(dget(r"Année de construction") or "")320 if y:321 out["year_built"] = y322 # clé canonique Centris pour finalize() (aire en MC = m², convertie)323 aire = dget(r"Aire habitable")324 if aire:325 details.setdefault("Superficie habitable", aire)326 out["details"] = details327 return out328