SPB Git

Repository Public

royal_lepage.py 15.0 KB 344 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Immo·Ka9# File             : immoka/connectors/royal_lepage.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/royal_lepage.py : Royal LePage (royallepage.ca) — Québec91#92#   Le portail rend ses résultats côté serveur, mais /fr/search/homes/{page}/93#   sans géo renvoie le Canada entier. La recherche par ville EST filtrable :94#   /fr/search/homes/{page}/?search_str=...&prov_code=QC&city_name=...&lat=..&95#   lng=..&search_type=city renvoie 100 % de propriétés du Québec, classées par96#   proximité (46/page). Chaque recherche plafonne à ~1 250 résultats ; on97#   SHARD donc par points d'ancrage répartis dans la province et on dédoublonne98#   par numéro MLS (= n° Centris, dans l'URL /.../mls{no}/). Aucune dépendance99#   Firecrawl : requêtes directes.100# -----------------------------------------------------------------------------101from __future__ import annotations102103import html as _html104import os105import re106107from .base import BaseConnector108from . import _detailutil as du109from ..normalize import parse_price110from ..schema import PropertyListing111112BASE = "https://www.royallepage.ca/fr/search/homes"113MAX_PAGES = 30                        # une recherche plafonne à ~27 pages (~1250)114# Le nom du BUREAU (« Royal LePage Humania »…) n'est pas sur la carte : il vient115# de la fiche détail. Enrichissement plafonné + cache (agency se remplit au fil116# des cycles). = affichage des Sources par sous-agence.117DETAIL_LIMIT = int(os.environ.get("IMMOKA_RLP_DETAIL_LIMIT", "500"))118_OFFICE_RE = re.compile(r'agent-info__brokerage".*?<a[^>]*>\s*([^<,\n]+?)\s*(?:,|\n|</a>)',119                        re.S | re.I)120121# Points d'ancrage couvrant le Québec (nom, lat, lng). L'union des recherches122# + dédoublonnage MLS couvre la province.123ANCHORS = [124    ("Montréal", 45.5089, -73.5542), ("Québec", 46.8139, -71.2080),125    ("Gatineau", 45.4765, -75.7013), ("Sherbrooke", 45.4040, -71.8929),126    ("Trois-Rivières", 46.3432, -72.5432), ("Saguenay", 48.4280, -71.0680),127    ("Laval", 45.6066, -73.7124), ("Longueuil", 45.5312, -73.5185),128    ("Drummondville", 45.8833, -72.4833), ("Saint-Jérôme", 45.7803, -74.0038),129    ("Granby", 45.4001, -72.7300), ("Rimouski", 48.4489, -68.5236),130    ("Rouyn-Noranda", 48.2360, -79.0230), ("Val-d'Or", 48.0975, -77.7972),131    ("Gaspé", 48.8330, -64.4870), ("Sept-Îles", 50.2001, -66.3821),132    ("Baie-Comeau", 49.2166, -68.1487), ("Joliette", 46.0167, -73.4500),133    ("Saint-Hyacinthe", 45.6300, -72.9569), ("Sorel-Tracy", 46.0500, -73.1200),134    ("Victoriaville", 46.0533, -71.9667), ("Mont-Laurier", 46.5500, -75.5000),135    ("Alma", 48.5500, -71.6500), ("Matane", 48.8500, -67.5300),136    ("Saint-Sauveur", 45.8939, -74.2051), ("Baie-Saint-Paul", 47.4400, -70.5000),137    ("Salaberry-de-Valleyfield", 45.2500, -74.1300), ("Thetford Mines", 46.1000, -71.3000),138]139140_CARD_RE = re.compile(r'card--listing-card js-listing js-property-details(.*?)'141                      r'(?=card--listing-card js-listing js-property-details|</main>|$)', re.S)142_URL_RE = re.compile(r'/fr/property/quebec/[^"\']+?/mls[a-z0-9]+/', re.I)143_MLS_RE = re.compile(r'/mls([a-z0-9]+)/', re.I)144_KEY_RE = re.compile(r'data-rlp-key="(-?\d+\.\d+)\.(-?\d+\.\d+)"')145_PHOTO_RE = re.compile(r'(//rlp\.jumplisting\.com/photos/[^"\']+)')146_CAC_RE = re.compile(r'(\d+)\s*CAC', re.I)147_SDB_RE = re.compile(r'(\d+)(?:\+\d+)?\s*SDB', re.I)148_PRICE_RE = re.compile(r'([\d\s  ]{4,})\s*\|?\s*\$')149_TYPE_RE = re.compile(r'\|\s*(Maison|Condo|Appartement|Duplex|Triplex|Plex|Terrain|'150                      r'Chalet|Fermette|Ferme|Loft|Terre|Maison de ville|Jumelé|'151                      r'Quadruplex|Quintuplex|Commercial)\s*\|', re.I)152153154class RoyalLepageConnector(BaseConnector):155    source_id = "royal_lepage"156    request_delay = 0.4157158    def fetch(self) -> list[PropertyListing]:159        by_id: dict[str, PropertyListing] = {}160        for name, lat, lng in ANCHORS:161            self._search_anchor(name, lat, lng, by_id)162        listings = list(by_id.values())163        # fiche détail (server-rendered, requêtes directes) : description164        # (« Remarques »), année (« Bâti en »), superficies, salles d'eau,165        # taxes/évaluations, frais de copropriété, date d'inscription, bureau.166        # v2 = parse complet (l'ancien « office1 » ne captait que le bureau).167        du.enrich(self, listings, DETAIL_LIMIT, _parse_rlp_detail, key="v2")168        for lst in listings:169            office = lst.details.pop("__agency", "")170            if office:171                lst.agency = office172        return listings173174    def _search_anchor(self, name: str, lat: float, lng: float, out: dict) -> None:175        empty_streak = 0176        for page in range(1, MAX_PAGES + 1):177            params = {178                "search_str": f"{name}, QC", "prov_code": "QC",179                "city_name": name, "lat": lat, "lng": lng, "search_type": "city",180            }181            try:182                html = self.get(f"{BASE}/{page}/", params=params,183                                headers={"X-Requested-With": "XMLHttpRequest"}).text184            except Exception:185                break186            new = 0187            for lst in self._parse_cards(html):188                if lst.external_id not in out:189                    out[lst.external_id] = lst190                    new += 1191            if new == 0:192                empty_streak += 1193                if empty_streak >= 2:   # cap serveur atteint (page répétée)194                    break195            else:196                empty_streak = 0197198    def _parse_cards(self, html: str) -> list[PropertyListing]:199        out = []200        for seg in _CARD_RE.findall(html):201            murl = _URL_RE.search(seg)202            if not murl:203                continue204            url = "https://www.royallepage.ca" + murl.group(0)205            mls = _MLS_RE.search(url)206            ext = mls.group(1) if mls else url207            # /fr/property/quebec/{ville}/{adresse}/{id}/mls{no}/208            parts = murl.group(0).strip("/").split("/")209            city = parts[3].replace("-", " ").title() if len(parts) > 3 else ""210            address = parts[4].replace("-", " ").title() if len(parts) > 4 else ""211            flat = _html.unescape(re.sub(r"<[^>]+>", " | ", seg))212            flat = re.sub(r"(\s*\|\s*)+", " | ", re.sub(r"\s+", " ", flat))213            beds = _CAC_RE.search(flat)214            baths = _SDB_RE.search(flat)215            price = _PRICE_RE.search(flat)216            typ = _TYPE_RE.search(flat)217            key = _KEY_RE.search(seg)218            photo = _PHOTO_RE.search(seg)219            images = []220            if photo:221                images = ["https:" + photo.group(1).replace("_0_med", "_0_lg")]222            out.append(PropertyListing(223                source=self.source_id, external_id=str(ext), url=url,224                title=address, address=address, city=city, region="Québec",225                property_type=(typ.group(1) if typ else ""),226                price=(parse_price(price.group(1)) if price else None),227                price_label=(price.group(0).strip() if price else ""),228                bedrooms=int(beds.group(1)) if beds else None,229                bathrooms=int(baths.group(1)) if baths else None,230                mls=(mls.group(1) if mls else ""),231                images=images,232                lat=float(key.group(1)) if key else None,233                lng=float(key.group(2)) if key else None,234                broker_name="Royal LePage",235            ))236        return out237238239def _parse_rlp_office(html: str) -> dict:240    """Extrait le bureau/brokerage de la fiche détail Royal LePage."""241    m = _OFFICE_RE.search(html)242    if not m:243        return {}244    office = _html.unescape(m.group(1)).strip()245    return {"details": {"__agency": office}} if office else {}246247248def _sqft(val: str) -> float | None:249    """« 58932.38 Pieds carrés » / « 1163 Pieds carrés » / « 108 Mètres carrés »250    -> pi² (les fiches RLP écrivent l'unité en toutes lettres)."""251    m = re.search(r"([\d\s  ]+(?:[.,]\d+)?)\s*(pieds|m[èe]tres)\s+carr",252                  val or "", re.I)253    if not m:254        return None255    try:256        v = float(m.group(1).replace(" ", "").replace(" ", "").replace(",", "."))257    except ValueError:258        return None259    if v <= 0:260        return None261    return round(v) if m.group(2).lower().startswith("pied") else round(v * 10.7639)262263264# libellés « Libellé : | Valeur » de la fiche RLP -> clé details265_RLP_DETAILS = [266    "Frais de copropriété", "Taxes municipales", "Taxe scolaire",267    "Taxes annuelles totales", "Évaluation du terrain",268    "Évaluation de l'immeuble", "Évaluation totale", "Superficie habitable (approx)",269    "Superficie totale aménagée", "Dimensions du terrain", "Zonage", "Chauffage",270    "Sous-sol", "Toiture", "Style", "Type de structure",271    "Nbre d'espaces de stationnement", "Vue", "Égout", "Piscine",272]273_RLP_STOPS = ("Particularités du bâtiment", "Caractéristiques de", "Chauffage",274              "Détails |", "Carte |", "Données démographiques")275276277def _parse_rlp_detail(html: str) -> dict:278    """Fiche Royal LePage (server-rendered) : description, année, superficies,279    salles d'eau, taxes/évaluations, frais de condo, date d'inscription, bureau."""280    out: dict = _parse_rlp_office(html)281    flat = _html.unescape(re.sub(r"<[^>]+>", " | ", html))282    flat = re.sub(r"(\s*\|\s*)+", " | ", re.sub(r"[ \t\r\n]+", " ", flat))283284    def field(label: str) -> str:285        m = re.search(re.escape(label) + r"\s*:?\s*\|\s*([^|]{1,70})\s*\|", flat)286        return m.group(1).strip() if m else ""287288    details = out.setdefault("details", {})289    for label in _RLP_DETAILS:290        v = field(label)291        if v and v.rstrip(" :") not in _RLP_DETAILS:292            details[label] = v293294    # description = section « Remarques : » (paragraphes séparés par des |)295    md = re.search(r"Remarques\s*:\s*\|\s*(.{80,8000}?)\s*\|\s*(?:"296                   + "|".join(re.escape(s) for s in _RLP_STOPS) + ")", flat)297    if md:298        desc = re.sub(r"\s*\|\s*", "\n", md.group(1)).strip()299        if len(desc) > 60:300            out["description"] = desc[:6000]301302    my = re.search(r"Bâti en\s*:?\s*\|\s*((?:1[6-9]|20)\d{2})\b", flat)303    if my:304        out["year_built"] = int(my.group(1))305    mb = re.search(r"Chambres\s*:?\s*\|\s*(\d+)\b", flat)306    if mb:307        out["bedrooms"] = int(mb.group(1))308    ms = re.search(r"Salle\(s\) de bains\s*:?\s*\|\s*(\d+)\b", flat)309    if ms:310        out["bathrooms"] = int(ms.group(1))311    mp = re.search(r"Salle\(s\) d'eau\s*:?\s*\|\s*(\d+)\b", flat)312    if mp and int(mp.group(1)) > 0:313        out["powder_rooms"] = int(mp.group(1))314    area = _sqft(details.get("Superficie habitable (approx)", ""))315    if not area:316        # « Superficie totale aménagée » désigne parfois le TERRAIN aménagé :317        # on ne s'en sert que si la valeur est plausible pour de l'habitable318        a2 = _sqft(details.get("Superficie totale aménagée", ""))319        if a2 and a2 <= 6000:320            area = a2321    if area:322        out["area_sqft"] = area323    lot = _sqft(details.get("Dimensions du terrain", ""))324    if lot:325        out["lot_sqft"] = lot326327    # date d'inscription (JSON-LD datePosted « 2026/08/12 »)328    mdp = re.search(r'"datePosted"\s*:\s*"(\d{4})/(\d{2})/(\d{2})"', html)329    if mdp:330        details["listed_at"] = "-".join(mdp.groups())331332    # galerie : photos jumplisting (la carte liste n'en donne qu'une)333    imgs, seen = [], set()334    for m in re.finditer(r'(//rlp\.jumplisting\.com/photos/[^"\'\s]+?\.jpg)', html):335        u = "https:" + m.group(1)336        if u not in seen:337            seen.add(u)338            imgs.append(u)339    if len(imgs) > 1:340        out["images"] = imgs[:60]341    if not details:342        out.pop("details", None)343    return out344
Files main
Menu

Theme