SPB Git

Repository Public

sothebys_quebec.py 15.5 KB 365 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Immo·Ka9# File             : immoka/connectors/sothebys_quebec.py10# Module           : immoka11# Repository       : https://git.spboucher.ai/immo-ka12# Created          : 2026-08-1213# Last Modified    : 2026-08-1814#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/sothebys_quebec.py : Sotheby's International Realty Québec91#   Inventaire COMPLET via l'API AJAX interne du site :92#     GET /include/ajax_results.php?dowhat=getgridresults&token=…&p_territories[]=493#   (territoire 4 = province de Québec ; jeton `ajaxtoken` exposé dans la page94#   /en/search-results/province-quebec-real-estate/). Pagination 64 fiches/page.95#   Particularité serveur : les valeurs du filtre statut de l'interface96#   (1 = For Sale, 3 = For Rent) sont REMAPPÉES côté serveur — `p_status[]=1`97#   renvoie 0 résultat et `p_status[]=3` seulement les locations. On passe donc98#   une valeur neutre (2) qui désactive le filtre et renvoie TOUT l'inventaire99#   actif (vente + location), puis on écarte les locations (« …/mo ») au parsing.100#   Chaque carte porte data-lat/lng/img/price + adresse/ville + CAC/SDB.101#   Enrichissement fiche détail (JSON-LD Product) : prix, galerie S3 complète,102#   description, n° MLS = sku. Repli : ancien parcours des pages région si103#   l'AJAX venait à changer.104# -----------------------------------------------------------------------------105from __future__ import annotations106107import html as _html108import json109import os110import re111112from .base import BaseConnector113from . import _detailutil as du114from ..schema import PropertyListing115116SITE = "https://sothebysrealty.ca"117DETAIL_LIMIT = int(os.environ.get("IMMOKA_SOTHEBYS_DETAIL_LIMIT", "400"))118# ~18 pages × 64 = tout l'inventaire QC (~1 100 fiches) ; borne de sécurité.119MAX_PAGES = int(os.environ.get("IMMOKA_SOTHEBYS_MAX_PAGES", "30"))120QC_TERRITORY = 4          # p_territories[] = province de Québec121122# Régions administratives du Québec (repli si l'AJAX casse).123QC_REGIONS = [124    "region-montreal", "region-laval", "region-monteregie", "region-laurentides",125    "region-lanaudiere", "region-eastern-townships", "region-outaouais",126    "region-capitale-nationale", "region-mauricie", "region-centre-du-quebec",127    "region-chaudiere-appalaches", "region-bas-saint-laurent",128    "region-saguenay-lac-saint-jean", "region-cote-nord", "region-charlevoix",129    "region-gaspesie-iles-de-la-madeleine", "region-abitibi-temiscamingue",130]131132_PROP_RE = re.compile(133    r'/(?:fr|en)/property/quebec/region-([a-z-]+)/([a-z0-9-]+?)-real-estate/(\d{5,})/([a-z0-9-]+)/',134    re.I)135_TOKEN_RE = re.compile(r"var ajaxtoken = '([a-f0-9]+)'")136_CARD_SPLIT_RE = re.compile(r'(?=<div class="mprop )')137_ATTR_RE = re.compile(r'data-(lat|lng|img|price|id)="([^"]*)"')138_LOC_RE = re.compile(r'<p class="location">([^<]*)</p>')139_BED_RE = re.compile(r'(\d{1,2})\s*BEDS?', re.I)140_BATH_RE = re.compile(r'(\d{1,2})\s*BATHS?', re.I)141142143class SothebysQuebecConnector(BaseConnector):144    source_id = "sothebys_quebec"145    request_delay = 1.0146147    def _get_tolerant(self, url: str) -> str:148        """GET qui ignore le statut HTTP : certaines pages Sotheby's renvoient149        un 404 tout en servant le contenu complet."""150        import time151        wait = self.request_delay - (time.time() - self._last_request)152        if wait > 0:153            time.sleep(wait)154        resp = self.session.get(url, timeout=self.timeout)155        self._last_request = time.time()156        return resp.text157158    # -- API AJAX interne -------------------------------------------------------159    def _ajax_token(self) -> str:160        html = self._get_tolerant(161            f"{SITE}/en/search-results/province-quebec-real-estate/")162        m = _TOKEN_RE.search(html)163        return m.group(1) if m else ""164165    def _ajax_page(self, token: str, page: int) -> dict:166        params = {167            "dowhat": "getgridresults", "token": token, "agent_slug": "",168            "aid": 0, "team_id": 0, "view": "grid", "sort": 1,169            "p_bed": 0, "p_bath": 0, "p_mls": 1, "p_minprice": 0,170            "p_maxprice": 0, "p_status[]": 2, "p_territories[]": QC_TERRITORY,171            "search_type_init": 2, "per_page": 64, "per_page_init": 64,172            "page": page, "map_data": 0, "device": "desktop",173            "device_width": 1440, "start": "", "crawler": 0, "office": 0,174            "development": 0, "igallery": 0, "boundary_trap": 0,175            "pagetype": "", "do_int": 0, "extrasearch": "", "results_qty": 0,176        }177        resp = self.get(f"{SITE}/include/ajax_results.php", params=params,178                        headers={"X-Requested-With": "XMLHttpRequest",179                                 "Referer": f"{SITE}/en/search-results/"})180        try:181            return resp.json()182        except ValueError:183            return {}184185    def fetch(self) -> list[PropertyListing]:186        by_id: dict[str, PropertyListing] = {}187        try:188            token = self._ajax_token()189            if token:190                total = None191                for page in range(1, MAX_PAGES + 1):192                    data = self._ajax_page(token, page)193                    cards_html = (data or {}).get("properties") or ""194                    if total is None:195                        try:196                            total = int(data.get("results") or 0)197                        except (TypeError, ValueError):198                            total = 0199                    found = False200                    for card in _CARD_SPLIT_RE.split(cards_html):201                        if 'data-id="' not in card:202                            continue203                        found = True204                        lst = self._card_to_listing(card)205                        if lst and lst.external_id not in by_id:206                            by_id[lst.external_id] = lst207                    if not found or (total and len(by_id) >= total):208                        break209        except Exception:210            pass211        if not by_id:  # repli : parcours des pages région (ancienne méthode)212            for region in QC_REGIONS:213                url = f"{SITE}/en/search-results/{region}-province-quebec-real-estate/"214                try:215                    html = self._get_tolerant(url)216                except Exception:217                    continue218                for m in _PROP_RE.finditer(html):219                    lst = self._to_listing(m)220                    if lst and lst.external_id not in by_id:221                        by_id[lst.external_id] = lst222        listings = list(by_id.values())223        # fiche détail : JSON-LD Product (prix, galerie complète, description, MLS)224        du.enrich(self, listings, DETAIL_LIMIT, parse_sothebys_detail, key="v1")225        return listings226227    def _card_to_listing(self, card: str) -> PropertyListing | None:228        attrs = dict(_ATTR_RE.findall(card))229        pid = attrs.get("id")230        if not pid:231            return None232        price_label = _html.unescape(attrs.get("price") or "").strip()233        # hors périmètre « à vendre » : locations («…/mo») et fiches sans prix234        # affiché (« Sold », « Price upon request »…) — p_status neutre renvoie235        # tout l'inventaire, on filtre ici.236        if "/mo" in price_label or not re.search(r"\d", price_label):237            return None238        m = _PROP_RE.search(card)239        if m:240            region_slug, city_slug, _, addr_slug = m.groups()241            url = (f"{SITE}/fr/property/quebec/region-{region_slug}/"242                   f"{city_slug}-real-estate/{pid}/{addr_slug}/")243            region = _deslug(region_slug)244        else:245            url = f"{SITE}/en/property/{pid}/"246            region = ""247        loc = _LOC_RE.search(card)248        address = city = ""249        title = ""250        if loc:251            title = _html.unescape(loc.group(1)).strip()252            parts = [p.strip() for p in title.split(",")]253            address = parts[0] if parts else ""254            # "28 Av. de la Gare, Saint-Sauveur, Quebec" → ville = avant-dernier255            if len(parts) >= 2:256                city = parts[-2] if parts[-1].lower() in ("quebec", "québec") \257                    else parts[-1]258        if not title and m:259            title = _deslug(m.group(4))260        lst = PropertyListing(261            source=self.source_id,262            external_id=str(pid),263            url=url,264            title=title,265            address=address,266            city=city,267            region=region,268            price_label=price_label,269            broker_name="Sotheby's International Realty Québec",270        )271        mb = _BED_RE.search(card)272        if mb and int(mb.group(1)) <= 20:273            lst.bedrooms = int(mb.group(1))274        ms = _BATH_RE.search(card)275        if ms and int(ms.group(1)) <= 20:276            lst.bathrooms = int(ms.group(1))277        try:278            lst.lat = float(attrs.get("lat") or "")279            lst.lng = float(attrs.get("lng") or "")280        except ValueError:281            lst.lat = lst.lng = None282        img = attrs.get("img") or ""283        if img:284            lst.images = [re.sub(r'(?:nr|m)?\.jpg$', 'r.jpg', img)]285        return lst286287    def _to_listing(self, m: re.Match) -> PropertyListing | None:288        region_slug, city_slug, pid, addr_slug = m.group(1), m.group(2), m.group(3), m.group(4)289        url = f"{SITE}/fr/property/quebec/region-{region_slug}/{city_slug}-real-estate/{pid}/{addr_slug}/"290        return PropertyListing(291            source=self.source_id,292            external_id=pid,293            url=url,294            title=_deslug(addr_slug),295            address=_deslug(addr_slug),296            city=_deslug(city_slug),297            region=_deslug(region_slug),298            broker_name="Sotheby's International Realty Québec",299        )300301302def parse_sothebys_detail(html: str) -> dict:303    """Extrait le JSON-LD Product : prix, galerie S3 complète, description, MLS."""304    out: dict = {}305    for node in du.ld_nodes(html):306        if node.get("@type") != "Product":307            continue308        offers = node.get("offers") or {}309        if isinstance(offers, list):310            offers = offers[0] if offers else {}311        price = offers.get("price")312        try:313            out["price"] = float(price) if price is not None else None314        except (TypeError, ValueError):315            pass316        if node.get("description"):317            out["description"] = _html.unescape(str(node["description"])).strip()318        if node.get("sku"):319            out["mls"] = str(node["sku"])320        cat = node.get("category")321        if cat:322            out["details"] = {"Type de propriété": str(cat)}323        break324325    # galerie complète : photos S3 de CETTE fiche (pleine résolution 'r'),326    # dédoublonnées par identifiant de base — plus complètes que le JSON-LD.327    mid = re.search(r'/live/images/listings/(\d+)/', html)328    if mid:329        lid = mid.group(1)330        seen, gallery = set(), []331        for u in re.findall(332                rf'https://sircmedia\.s3\.ca-central-1\.amazonaws\.com/live/images/listings/{lid}/'333                r'[^"\' ]+\.(?:jpg|jpeg|webp)', html):334            base = re.sub(r'(?:nr|m|r)?\.(?:jpg|jpeg|webp)$', '', u.rsplit("/", 1)[-1])335            full = re.sub(r'(?:nr|m)?\.jpg$', 'r.jpg', u)336            if base not in seen:337                seen.add(base)338                gallery.append(full)339        if gallery:340            out["images"] = gallery341    # repli sur les images du JSON-LD si aucune photo S3 trouvée342    if not out.get("images"):343        for node in du.ld_nodes(html):344            if node.get("@type") == "Product" and node.get("image"):345                imgs = node["image"]346                out["images"] = imgs if isinstance(imgs, list) else [imgs]347                break348349    # chambres / salles de bains (best-effort, valeurs plausibles seulement)350    text = re.sub(r"\s+", " ", _html.unescape(re.sub(r"<[^>]+>", " ", html)))351    mb = re.search(r"\b(\d{1,2})\s*(?:Bedroom|Chambre|bed\b|ch\.)", text, re.I)352    if mb and int(mb.group(1)) <= 20:353        out["bedrooms"] = int(mb.group(1))354    ms = re.search(r"\b(\d{1,2})\s*(?:Bathroom|Salle de bain|bath\b)", text, re.I)355    if ms and int(ms.group(1)) <= 20:356        out["bathrooms"] = int(ms.group(1))357    coords = du.gmaps_coords(html)358    if coords:359        out["lat"], out["lng"] = coords360    return out361362363def _deslug(s: str) -> str:364    return re.sub(r"\s+", " ", s.replace("-", " ")).strip().title()365
Files main
Menu

Theme