SPB Git

Repository Public

kw_prestige.py 10.9 KB 270 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Immo·Ka9# File             : immoka/connectors/kw_prestige.py10# Module           : immoka11# Repository       : https://git.spboucher.ai/immo-ka12# Created          : 2026-08-1213# 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/kw_prestige.py : Keller Williams Prestige (kwprestige.com)91#   Plateforme macleweb.com. La grille /fr/proprietes/ est servie par l'API92#   interne /ajax/getProps.php (JSON {html, nbPages}) : cartes complètes —93#   prix, adresse, ville (secteur), cac/sdb, mini-description, photo. Les94#   fiches détail sont rendues serveur : galerie complète (data-centris/95#   large_photo), description, tableau Centris, GPS (iframe maps/embed),96#   courtiers inscripteurs.97#   ⚠️ Ne PAS revenir au sitemap.xml : il est figé (lastmod 2025-09) et ses98#   fiches expirées rendent un gabarit vide (prix « 0 », aucune adresse).99#   ⚠️ Le site exige un User-Agent navigateur (curl nu → 403) ; l'UA de100#   BaseConnector passe.101# -----------------------------------------------------------------------------102from __future__ import annotations103104import html as _html105import os106import re107108from .base import BaseConnector109from . import _detailutil as du110from ..normalize import parse_price111from ..schema import PropertyListing112113BASE = "https://www.kwprestige.com"114AJAX = BASE + "/ajax/getProps.php?json=1&default_lang=fr&page={page}&qty=100"115DETAIL_LIMIT = int(os.environ.get("IMMOKA_KW_DETAIL_LIMIT", "400"))116117# carte de la grille : <a href='/{slug}-{id}-detail-Fr' class='proprieteitem'>…</a>118_CARD_RE = re.compile(119    r"<a href='(/[^']*?-(\d{6,9})-detail-Fr)' class='proprieteitem'>(.*?)</a>", re.S)120_PRICE_RE = re.compile(r"class='titre2'>(.*?)</p>", re.S)121_ADDR_RE = re.compile(r"class='titresm'>(.*?)</h3>\s*<p>(.*?)</p>", re.S)122_ICON_RE = re.compile(r"</svg>\s*(\d+)\s*</div>")123_MINIDESC_RE = re.compile(r"class='minidescription'>(.*?)</p>", re.S)124_THUMB_RE = re.compile(r"src='(https://www\.kwprestige\.com/data-centris/photo/[^']+)'")125126# fiche détail127_LARGE_RE = re.compile(128    r'https://www\.kwprestige\.com/data-centris/large_photo/[^"\'\\ ]+'129    r'\.(?:jpg|jpeg|png|webp)', re.I)130_DPRICE_RE = re.compile(r'<p class="prix">(.*?)</p>', re.S)131_DDESC_RE = re.compile(r'fichecdescription">.*?<p>(.*?)</p>', re.S)132_GPS_RE = re.compile(r'!2d(-?\d{2,3}\.\d+)!3d(-?\d{2}\.\d+)')133_BROKER_RE = re.compile(r'courtierfiche">.*?<h3 class="titresm">(.*?)</h3>', re.S)134_PHONE_RE = re.compile(r'href="tel:([+\d.\-]{7,})"')135_ROOM_RE = re.compile(r'class="nbr_(chambres|sdb|pieces)">\s*<img[^>]*>\s*(\d+)')136137# type de propriété depuis le slug d'URL (« {type}-a-vendre-… »)138_TYPE = [139    ("location-d-espace", "Commercial"), ("location-de", "Commercial"),140    ("location", "Commercial"),141    ("maison-etages", "Maison"), ("maison-paliers", "Maison"),142    ("maison-plain-pied", "Maison"), ("maison-mobile", "Maison mobile"),143    ("maison", "Maison"), ("appartement", "Condo"), ("condo", "Condo"),144    ("loft", "Condo"), ("duplex", "Duplex"), ("triplex", "Triplex"),145    ("quadruplex", "Multiplex"), ("quintuplex", "Multiplex"),146    ("propriete-revenu", "Multiplex"), ("terrain", "Terrain"),147    ("chalet", "Chalet"), ("fermette", "Fermette/Agricole"),148    ("ferme", "Fermette/Agricole"),149    ("local-commercial", "Commercial"), ("espace-commercial", "Commercial"),150    ("espace-industriel", "Commercial"), ("espace-bureau", "Commercial"),151    ("commerce", "Commercial"), ("bureau", "Commercial"),152    ("batisse", "Commercial"), ("industriel", "Commercial"),153]154155156def _txt(s: str) -> str:157    return _html.unescape(re.sub(r"<[^>]+>", " ", s or "")).replace("\xa0", " ").strip()158159160def _city_sector(label: str) -> tuple[str, str]:161    """« Montréal (Ville-Marie) » -> (Montréal, Ville-Marie)."""162    m = re.match(r"(.+?)\s*\((.+?)\)\s*$", label or "")163    if m:164        return m.group(1).strip(), m.group(2).strip()165    return (label or "").strip(), ""166167168class KwPrestigeConnector(BaseConnector):169    source_id = "kw_prestige"170    request_delay = 0.5171172    def fetch(self) -> list[PropertyListing]:173        by_id: dict[str, PropertyListing] = {}174        page = 1175        while page <= 50:                      # garde-fou176            data = self.get(AJAX.format(page=page)).json()177            for path, cid, block in _CARD_RE.findall(data.get("html") or ""):178                if cid not in by_id:179                    by_id[cid] = self._to_listing(path, cid, block)180            if page >= int(data.get("nbPages") or 1):181                break182            page += 1183        listings = list(by_id.values())184        du.enrich(self, listings, DETAIL_LIMIT, parse_kw_prestige_detail, key="v3")185        return listings186187    def _to_listing(self, path: str, cid: str, block: str) -> PropertyListing:188        m_price = _PRICE_RE.search(block)189        price_label = _txt(m_price.group(1)) if m_price else ""190        m_addr = _ADDR_RE.search(block)191        addr = _txt(m_addr.group(1)) if m_addr else ""192        city, sector = _city_sector(_txt(m_addr.group(2)) if m_addr else "")193        nums = _ICON_RE.findall(block)194        m_desc = _MINIDESC_RE.search(block)195        m_img = _THUMB_RE.search(block)196        slug = path.lstrip("/")197        typ_slug = re.split(r"-a-(?:vendre|louer)-", slug)[0]198        ptype = ""199        for key, canon in _TYPE:200            if typ_slug.startswith(key):201                ptype = canon202                break203        low = price_label.lower()204        status = "vendu" if low.startswith(("vendu", "loué", "loue")) else "a-vendre"205        return PropertyListing(206            source=self.source_id,207            external_id=cid,208            url=BASE + path,209            title=addr or _txt(price_label),210            status=status,211            address=addr,212            city=city,213            sector=sector,214            property_type=ptype,215            price=parse_price(price_label),216            price_label=price_label,217            bedrooms=int(nums[0]) if nums else None,218            bathrooms=int(nums[1]) if len(nums) > 1 else None,219            description=_txt(m_desc.group(1)) if m_desc else "",220            images=[m_img.group(1)] if m_img else [],221            mls=cid,222            broker_name="Keller Williams Prestige",223            agency="Keller Williams Prestige",224        )225226227def parse_kw_prestige_detail(html: str) -> dict:228    """Fiche détail macleweb : galerie complète, prix, description, tableau229    Centris, GPS (iframe Google Maps embed), courtiers, cac/sdb/pièces."""230    out: dict = {}231    seen, imgs = set(), []232    for u in _LARGE_RE.findall(html):233        if u not in seen:234            seen.add(u)235            imgs.append(u)236    if imgs:237        out["images"] = imgs238    m = _DPRICE_RE.search(html)239    if m:240        label = _txt(m.group(1))241        price = parse_price(label)242        if price:                                # « 0 » = gabarit vide/expiré243            out["price"] = price244            out["price_label"] = label245    m = _DDESC_RE.search(html)246    if m:247        d = _txt(m.group(1))248        if len(d) > 40:249            out["description"] = d250    m = _GPS_RE.search(html)251    if m:252        lng, lat = float(m.group(1)), float(m.group(2))253        if 44.5 <= lat <= 63.0 and -80.0 <= lng <= -56.0:254            out["lat"], out["lng"] = lat, lng255    m = _BROKER_RE.search(html)256    if m:257        out["broker_name"] = _txt(m.group(1))258    m = _PHONE_RE.search(html)259    if m:260        out["broker_phone"] = m.group(1)261    for key, n in _ROOM_RE.findall(html):262        if key == "chambres":263            out["bedrooms"] = int(n)264        elif key == "sdb":265            out["bathrooms"] = int(n)266    det = du.centris_details(du.flatten(html))267    if det:268        out.setdefault("details", {}).update(det)269    return out270
Files main
Menu

Theme