SPB Git

Repository Public

gwlra.py 12.9 KB 308 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/gwlra.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-2513# Last Modified    : 2026-09-0614#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# Lou-Ka — Agrégateur de logements à louer (province de Québec)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# connectors/gwlra.py : connecteur GWL Realty Advisors Residential91#   (gwlraresidential.com — gestionnaire pancanadien, plateforme RentCafe/Yardi92#   derrière Cloudflare : tout passe par Scrapfly ASP).93#   Découverte : sitemap.xml → pages /apartments/qc/<ville>/<slug>/floorplans94#   (immeubles du Québec seulement). Chaque page floorplans (rendu serveur)95#   expose les plans « div.fp-container » (id fp-container-<fpid>) avec le96#   prix « à partir de $X /mois » — seuls les plans avec prix sont retenus97#   (les autres = liste d'attente) — plus un JSON-LD ApartmentComplex98#   (adresse civique, animaux, chambres/sdb/pi² par plan). Une annonce par99#   plan d'étage disponible, external_id = <slug>-<fpid>.100# -----------------------------------------------------------------------------101from __future__ import annotations102103import json104import re105import time106107from bs4 import BeautifulSoup108109from ..schema import Listing, normalize_unit_type, parse_price110from .base import BaseConnector111112BASE = "https://www.gwlraresidential.com"113SITEMAP_URL = f"{BASE}/sitemap.xml"114115FLOORPLAN_PATH_RE = re.compile(116    r"apartments/qc/([a-z0-9-]+)/([a-z0-9-]+)/floorplans")117FPID_RE = re.compile(r"fp-container-(\d+)")118LDJSON_RE = re.compile(119    r'<script[^>]*type="application/ld\+json"[^>]*>(.*?)</script>', re.S)120TITLE_RE = re.compile(r"<title>\s*Plans d.étage au (.+?) à ", re.S)121PRICE_RE = re.compile(r"à partir de\s*\|?\s*(\$[\d,\s]+(?:\.\d{2})?)", re.I)122BED_RE = re.compile(r"(\d+)\s*\|\s*Chambre", re.I)123BATH_RE = re.compile(r"([\d.]+)\s*\|\s*Salle", re.I)124125# ville du chemin d'URL -> nom d'affichage126_CITIES = {"montreal": "Montréal", "laval": "Laval", "quebec": "Québec",127           "longueuil": "Longueuil", "brossard": "Brossard"}128129130class GwlraConnector(BaseConnector):131    source_id = "gwlra"132    request_delay = 1.0133    use_detail_cache = False        # tout passe par Scrapfly, pages fraîches134135    def fetch(self) -> list[Listing]:136        # Un raté transitoire (Scrapfly vide, vu 2026-08-30 ~04:20) produisait137        # un faux « 0 trouvé ok » (médiane 1) : retry du sitemap (3 essais,138        # backoff 5/10 s) puis erreur franche plutôt qu'un zéro silencieux.139        pages: dict[str, tuple[str, str]] = {}   # slug -> (ville, chemin)140        for attempt in range(3):141            try:142                sitemap = self.get_scrapfly(SITEMAP_URL, render_js=False)143            except Exception:144                if attempt == 2:145                    raise146                sitemap = ""147            for city, slug in FLOORPLAN_PATH_RE.findall(sitemap):148                pages.setdefault(slug, (city, f"apartments/qc/{city}/{slug}"149                                              "/floorplans"))150            if pages:151                break152            if attempt < 2:153                time.sleep(5 * (attempt + 1))154        if not pages:155            raise RuntimeError(156                "sitemap sans page floorplans QC après 3 essais")157158        listings: list[Listing] = []159        errors = 0160        last_exc: Exception | None = None161        for slug, (city_slug, path) in sorted(pages.items()):162            try:163                listings.extend(self._building(slug, city_slug,164                                               f"{BASE}/{path}"))165            except Exception as exc:166                errors += 1167                last_exc = exc168        # tous les immeubles en erreur et rien récolté : erreur franche169        if not listings and last_exc is not None and errors == len(pages):170            raise last_exc171        return listings172173    def _building(self, slug: str, city_slug: str, url: str) -> list[Listing]:174        # le sitemap contient des immeubles retirés (404) : vérifier le statut.175        # Les ratés transitoires (5xx, contenu vide) sont retentés 3 fois puis176        # remontés en erreur franche — seul un 404/410 vaut « immeuble retiré ».177        # Vu 2026-09-06 : Scrapfly renvoie parfois un rendu PARTIEL (200, ~7 Ko178        # de shell GTM/OneTrust sans grille de plans ni JSON-LD) → faux « 0179        # trouvé ok ». Une page floorplans complète contient toujours le180        # JSON-LD ApartmentComplex (rendu serveur), même sans dispo : exiger181        # fp-container OU ApartmentComplex avant d'accepter le HTML.182        html = ""183        for attempt in range(3):184            result = self.scrapfly(url, render_js=True)185            status = result.get("status_code")186            if status in (404, 410):187                return []188            html = result.get("content") or ""189            complete = "fp-container" in html or "ApartmentComplex" in html190            if status == 200 and html and complete:191                break192            if attempt < 2:193                time.sleep(5 * (attempt + 1))194        else:195            raise RuntimeError(196                f"page floorplans {url} en échec après 3 essais "197                f"(statut {status!r}, contenu "198                f"{'vide' if not html else 'partiel/incomplet'})")199        soup = BeautifulSoup(html, "html.parser")200201        # JSON-LD ApartmentComplex : nom, adresse, animaux, détail des plans202        # (extraction regex sur le HTML brut : le rendu Scrapfly est parfois203        # capricieux avec les <script> dans BeautifulSoup)204        name, address, pets = "", "", None205        hero = ""206        plans: dict[str, dict] = {}          # nom du plan -> détail JSON-LD207        blobs = [s.string or s.get_text() for s in208                 soup.find_all("script", type="application/ld+json")]209        blobs += LDJSON_RE.findall(html)210        for raw in blobs:211            try:212                d = json.loads(raw or "", strict=False)213            except (ValueError, TypeError):214                continue215            if not isinstance(d, dict) or "ApartmentComplex" not in \216                    str(d.get("@type", "")):217                continue218            name = (d.get("name") or "").strip()219            adr = d.get("address") or {}220            street = (adr.get("streetAddress") or "").strip()221            loc = (adr.get("addressLocality") or "").strip()222            postal = (adr.get("postalCode") or "").strip()223            address = ", ".join(x for x in (street, loc) if x)224            if address and postal:225                address += f", QC {postal}"226            if isinstance(d.get("petsAllowed"), bool):227                pets = "oui" if d["petsAllowed"] else "non"228            for fp in d.get("accommodationFloorPlan") or []:229                if isinstance(fp, dict) and fp.get("name"):230                    plans[fp["name"].strip().lower()] = fp231            if isinstance(d.get("image"), str):232                hero = d["image"]233            break234235        if not name:                          # repli : <title> de la page236            tm = TITLE_RE.search(html)237            if tm:238                name = tm.group(1).strip()239        city = _CITIES.get(city_slug, city_slug.replace("-", " ").title())240241        listings: list[Listing] = []242        for div in soup.select("div.fp-container[id]"):243            m = FPID_RE.search(div.get("id", ""))244            if not m:245                continue246            fpid = m.group(1)247            text = div.get_text(" | ", strip=True).replace("\xa0", " ")248            pm = PRICE_RE.search(text)249            if not pm:                       # pas de prix = liste d'attente250                continue251            fp_name = ""252            h = div.find(["h2", "h3", "h4", "strong"])253            if h:254                fp_name = h.get_text(" ", strip=True)255            if not fp_name:256                fp_name = text.split(" | ", 1)[0]257258            bedrooms = bathrooms = None259            area = None260            bm = BED_RE.search(text)261            if bm:262                bedrooms = float(bm.group(1))263            am = BATH_RE.search(text)264            if am:265                try:266                    bathrooms = float(am.group(1))267                except ValueError:268                    pass269            fp = plans.get(fp_name.strip().lower())270            if fp:271                if bedrooms is None and fp.get("numberOfBedrooms") is not None:272                    bedrooms = float(fp["numberOfBedrooms"])273                if bathrooms is None and \274                        fp.get("numberOfFullBathrooms") is not None:275                    bathrooms = float(fp["numberOfFullBathrooms"])276                size = fp.get("floorSize") or {}277                if isinstance(size, dict) and size.get("minValue"):278                    area = float(size["minValue"])279280            images = []281            for img in div.find_all("img"):282                u = img.get("src") or img.get("data-src") or ""283                if u.startswith("http"):284                    images.append(u)285            if hero:286                images.append(hero)287288            price_label = f"À partir de {pm.group(1)}/mois"289            listings.append(Listing(290                source=self.source_id,291                external_id=f"{slug}-{fpid}",292                url=url,293                title=f"{name or slug} — {fp_name}",294                address=address,295                sector="",296                city=city,297                unit_type=normalize_unit_type(fp_name),298                bedrooms=bedrooms,299                bathrooms=bathrooms,300                price=parse_price(pm.group(1)),301                price_label=price_label,302                availability="Disponible",303                area_sqft=area,304                pets=pets,305                images=list(dict.fromkeys(images))[:10],306            ))307        return listings308
Files main
Menu

Theme