Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Immo·Ka9# File : immoka/connectors/bhhs_quebec.py10# Module : immoka11# Repository : https://git.spboucher.ai/immo-ka12# Created : 2026-08-1613# Last Modified : 2026-08-1914#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/bhhs_quebec.py : Berkshire Hathaway HomeServices Québec91# (bhhsquebec.ca) — Grand Montréal, Laurentides, Montérégie, Outaouais.92# Site WordPress (plugin « MW Properties » / realestate.marketingwebsites.ca),93# liste rendue SERVEUR sur /proprietes/, paginée par ?pages=N (~9/page,94# ~11 pages). Chaque carte porte : n° Centris (URL + image + property-meta),95# région, adresse, ville, prix ($US), chambres/sdb et photo.96#97# Page détail : description + addenda (<div class="description block">,98# collapse #showAddendum), bloc « features » (Année de construction, pièces,99# chambres, sdb… en h5/p), tableau « Caractéristiques » (#charateristics —100# sic — th/td), GPS inline (google.maps.LatLng(lat,lng)), visite virtuelle101# (iframe #virtualCollapse), courtier (.agents : nom + tel:) et galerie102# complète property-images/{Centris}/{Centris}-NN.jpg (pleine résolution,103# ordre d'origine ; les miniatures /thumbs-320/ sont ignorées).104# Enrichissement plafonné + cache (du.enrich).105#106# source_id « bhhs_ag_qc » : infixe _ag_ = dédup Centris (db.refresh_dedup).107# -----------------------------------------------------------------------------108from __future__ import annotations109110import html as _html111import os112import re113import urllib.parse114115from .base import BaseConnector116from . import _detailutil as du117from ..normalize import parse_price118from ..schema import PropertyListing119120SITE = "https://bhhsquebec.ca"121LISTING = SITE + "/proprietes/"122DETAIL_LIMIT = int(os.environ.get("IMMOKA_BHHS_DETAIL_LIMIT", "150"))123AGENCY = "Berkshire Hathaway HomeServices Québec"124125_CARD_SPLIT = re.compile(r'<a href="(https://bhhsquebec\.ca/properties/[^"]*?/(\d{6,9}))"\s+class="list"', re.I)126_IMG_RE = re.compile(r'(https://realestate\.marketingwebsites\.ca/property-images/\d+/[^"\']+\.(?:jpg|jpeg|png|webp))', re.I)127_REGION_RE = re.compile(r'<h3>.*?</i>\s*([^<]+)</h3>', re.S | re.I)128_ADDR_RE = re.compile(r'<div class="top-ctn">.*?<p>([^<]+)</p>', re.S | re.I)129_PRICE_RE = re.compile(r'class="price">\s*(\$[\d,]+|[\d\s ]+\$)', re.I)130_AMEN_RE = re.compile(r'(?:bed|hotel)[^>]*></i>\s*(\d+).*?(?:bath|shower)[^>]*></i>\s*(\d+)', re.S | re.I)131132# --- page détail ---133_GALLERY_RE = re.compile(134 r'https://realestate\.marketingwebsites\.ca/property-images/\d+/\d+-\d+'135 r'\.(?:jpg|jpeg|png|webp)', re.I)136_P_RE = re.compile(r'<p[^>]*>(.*?)</p>', re.S | re.I)137_CHAR_ROW_RE = re.compile(r'<th[^>]*>(.*?)</th>\s*<td[^>]*>(.*?)</td>', re.S | re.I)138_FEAT_RE = re.compile(r'<h5 class="title">([^<]+)</h5>\s*<p>([^<]*)</p>', re.I)139_LATLNG_RE = re.compile(r'google\.maps\.LatLng\(\s*(-?\d{1,2}\.\d+)\s*,\s*(-?\d{2,3}\.\d+)\s*\)')140_AGENT_RE = re.compile(r'class="agents">.*?<h3 class="name">([^<]+)</h3>(.*?)</ul>', re.S | re.I)141_TEL_RE = re.compile(r'href="tel:(\+?\d{7,11})"')142_IFRAME_RE = re.compile(r'<iframe[^>]+src="([^"]+)"', re.I)143144# libellés du bloc « features » promus en colonnes ; le reste va dans details145_FEAT_FIELDS = {146 "Année de construction": "year_built",147 "Chambre(s) à coucher": "bedrooms",148 "Salle(s) de bain": "bathrooms",149 "Salle(s) d'eau": "powder_rooms",150}151152153class BhhsQuebecConnector(BaseConnector):154 source_id = "bhhs_ag_qc"155 request_delay = 0.4156 max_pages = 40157158 def fetch(self) -> list[PropertyListing]:159 by_id: dict[str, PropertyListing] = {}160 dry = 0161 for page in range(1, self.max_pages + 1):162 url = LISTING if page == 1 else f"{LISTING}?pages={page}"163 try:164 html = self.get(url).text165 except Exception:166 break167 before = len(by_id)168 parts = _CARD_SPLIT.split(html)169 # parts = [pre, url1, mls1, blk1, url2, mls2, blk2, …]170 for i in range(1, len(parts) - 2, 3):171 url_p, mls, blk = parts[i], parts[i + 1], parts[i + 2][:1800]172 lst = self._card(url_p, mls, blk)173 if lst:174 by_id.setdefault(lst.external_id, lst)175 dry = dry + 1 if len(by_id) == before else 0176 if dry >= 2:177 break178 listings = list(by_id.values())179 du.enrich(self, listings, DETAIL_LIMIT, _parse_detail, key="v1")180 return listings181182 def _card(self, url_p: str, mls: str, blk: str) -> PropertyListing | None:183 addr, city = "", ""184 am = _ADDR_RE.search(blk)185 if am:186 raw = _html.unescape(am.group(1)).strip()187 if "," in raw:188 addr, city = [x.strip() for x in raw.rsplit(",", 1)]189 else:190 addr = raw191 if not addr:192 um = re.search(r'/properties/([^/]+)/\d{6,9}', url_p)193 if um:194 addr = _html.unescape(urllib.parse.unquote_plus(um.group(1))).strip()195196 rm = _REGION_RE.search(blk)197 region = _html.unescape(rm.group(1)).strip() if rm else ""198 pm = _PRICE_RE.search(blk)199 price_label = pm.group(1).strip() if pm else ""200 price = parse_price(price_label.replace("$", "").replace(",", "")) \201 if price_label.startswith("$") else parse_price(price_label)202 amn = _AMEN_RE.search(blk)203 im = _IMG_RE.search(blk)204205 return PropertyListing(206 source=self.source_id,207 external_id=mls,208 url=url_p,209 title=addr or "Propriété à vendre",210 address=addr,211 city=city,212 region=region,213 price=price,214 price_label=price_label,215 bedrooms=int(amn.group(1)) if amn else None,216 bathrooms=int(amn.group(2)) if amn else None,217 mls=mls,218 images=[im.group(1)] if im else [],219 agency=AGENCY,220 broker_name=AGENCY,221 )222223224def _txt(fragment: str) -> str:225 t = _html.unescape(re.sub(r"<br\s*/?>", "\n", fragment, flags=re.I))226 t = re.sub(r"<[^>]+>", " ", t).replace("\xa0", " ")227 t = re.sub(r"[ \t]+", " ", t)228 return re.sub(r"\n{3,}", "\n\n", t).strip()229230231def _parse_detail(html: str) -> dict:232 """Fiche détail BHHS (MW Properties) : description+addenda, features,233 caractéristiques, GPS, visite virtuelle, courtier, galerie complète."""234 out: dict = {}235236 # description : <p> du bloc description + addenda (collapse #showAddendum)237 i = html.find('class="description block')238 if i >= 0:239 j = html.find('id="addendum-btn"', i)240 if j < 0:241 j = html.find('class="char block"', i)242 seg = html[i:j if j > 0 else i + 30000]243 paras = [_txt(p) for p in _P_RE.findall(seg)]244 desc = "\n\n".join(p for p in paras if p)245 if desc:246 out["description"] = desc247248 details: dict = {}249 # bloc « features » (année, pièces, chambres, sdb…)250 for lab, val in _FEAT_RE.findall(html):251 lab, val = _txt(lab), _txt(val)252 if not val:253 continue254 field = _FEAT_FIELDS.get(lab)255 if field:256 m = re.search(r"\d+", val)257 if m:258 out[field] = int(m.group())259 elif len(val) <= 120:260 details[lab] = val261262 # tableau « Caractéristiques » (th/td)263 i = html.find('id="charateristics"')264 if i >= 0:265 seg = html[i:html.find("</table>", i)]266 for th, td in _CHAR_ROW_RE.findall(seg):267 lab, val = _txt(th), _txt(td)268 if lab and val and len(lab) <= 60 and len(val) <= 250:269 details[lab] = val270271 # GPS inline272 m = _LATLNG_RE.search(html)273 if m:274 lat, lng = float(m.group(1)), float(m.group(2))275 if 44.5 <= lat <= 63.0 and -80.0 <= lng <= -56.0:276 out["lat"], out["lng"] = lat, lng277278 # visite virtuelle (iframe du collapse dédié)279 i = html.find('id="virtualCollapse"')280 if i >= 0:281 m = _IFRAME_RE.search(html[i:i + 3000])282 if m and m.group(1).startswith("http"):283 details["Visite virtuelle"] = m.group(1)284285 # courtier inscripteur (carte .agents)286 m = _AGENT_RE.search(html)287 if m:288 out["broker_name"] = _txt(m.group(1))289 t = _TEL_RE.search(m.group(2))290 if t:291 tel = t.group(1).lstrip("+")292 if len(tel) == 10:293 tel = f"({tel[:3]}) {tel[3:6]}-{tel[6:]}"294 out["broker_phone"] = tel295296 if details:297 out["details"] = details298299 # galerie pleine résolution (sans /thumbs-320/), ordre d'origine300 seen, uniq = set(), []301 for u in _GALLERY_RE.findall(html):302 if u not in seen:303 seen.add(u)304 uniq.append(u)305 if not uniq:306 # toutes les fiches BHHS ont une galerie (flux Centris) ; une page sans307 # galerie = rendu transitoirement dégradé (l'API images du plugin MW a308 # flanché) → échec de parse : on ne met PAS en cache un payload sans309 # photos, la fiche sera réessayée au prochain cycle (du.enrich garde310 # l'éventuel payload périmé en attendant)311 return {}312 out["images"] = uniq313 return out314