SPB Git

Repository Public

girescom.py 13.5 KB 341 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/girescom.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-0813# Last Modified    : 2026-08-0914#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/girescom.py : connecteur Girescom (girescom.com)91#   Site RentSync rendu serveur. Liste /residential : une carte par immeuble92#   (adresse avec ville, prix « À partir de », fourchette de chambres).93#   Page immeuble /residential/<slug> : tableau des unités disponibles94#   (li.unit-table-desktop__units--unit, attributs column-field structurés :95#   numéro, chambres, sdb, prix, pi², photos, plan d'étage, disponibilité),96#   description « À propos de la propriété », commodités (immeuble + unité),97#   téléphone de l'immeuble et galerie. Une annonce Lou-Ka = une unité.98#   Périmètre : tout le portefeuille — Québec/Lévis, proche périphérie99#   (Sainte-Brigitte-de-Laval, Shannon…) et Beauce (Saint-Georges,100#   Sainte-Marie, Vallée-Jonction…) depuis l'expansion provinciale.101#   Fiches immeuble via self.detail() (cache BD, max max_details/sync).102# -----------------------------------------------------------------------------103from __future__ import annotations104105import hashlib106import re107108from bs4 import BeautifulSoup109110from ..schema import Listing, normalize_unit_type, parse_price, strip_accents111from .base import BaseConnector112113BASE = "https://www.girescom.com"114LIST_URL = f"{BASE}/residential"115116# Noms canoniques (accents/abréviations) des villes rencontrées dans les117# adresses — clé = forme normalisée (_city_key).118_CITY_CANON = {119    "quebec": "Québec",120    "levis": "Lévis",121    "saint-georges": "Saint-Georges", "st-georges": "Saint-Georges",122    "sainte-marie": "Sainte-Marie", "ste-marie": "Sainte-Marie",123    "vallee-jonction": "Vallée-Jonction",124    "saint-joseph-de-beauce": "Saint-Joseph-de-Beauce",125    "st-joseph-de-beauce": "Saint-Joseph-de-Beauce",126    "beauceville": "Beauceville",127    "saint-victor": "Saint-Victor",128    "east-broughton": "East Broughton",129    "tring-jonction": "Tring-Jonction",130    "saints-anges": "Saints-Anges",131    "scott": "Scott",132    "saint-elzear": "Saint-Elzéar", "st-elzear": "Saint-Elzéar",133    "frampton": "Frampton",134    "sainte-brigitte-de-laval": "Sainte-Brigitte-de-Laval",135    "shannon": "Shannon",136}137138# téléphone du siège social (affiché sur toutes les pages) — pas celui139# de l'immeuble140_CORPORATE_PHONE = "4186863040"141142143def _city_key(city: str) -> str:144    return re.sub(r"[\s']+", "-", strip_accents(city.strip().lower()))145146147def _unit_type(bed: str) -> str:148    """Chambres (colonne structurée) -> type Lou-Ka : 0 = Studio, n = (n+2)½."""149    b = (bed or "").strip()150    if b == "0":151        return "Studio"152    if b.isdigit():153        return normalize_unit_type(f"{b} chambres")154    return ""155156157class GirescomConnector(BaseConnector):158    source_id = "girescom"159    request_delay = 0.6160    max_details = 30     # garde-fou pages immeuble (vraies requêtes par sync)161162    def fetch(self) -> list[Listing]:163        # le serveur n'annonce pas charset=utf-8 : forcer le décodage164        resp = self.get(LIST_URL)165        resp.encoding = "utf-8"166        html = resp.text167        soup = BeautifulSoup(html, "html.parser")168169        self._fetched = 0170        listings: list[Listing] = []171        for card in soup.select("ul.card-grouping-grid li.card-grouping-grid__item"):172            try:173                listings.extend(self._parse_building(card))174            except Exception:175                continue176        return listings177178    # -- carte immeuble (liste /residential) -------------------------------------179    def _parse_building(self, card) -> list[Listing]:180        link = card.select_one('a[href^="/residential/"]')181        if not link:182            return []183        slug = link["href"].rstrip("/").rsplit("/", 1)[-1]184        url = f"{BASE}/residential/{slug}"185186        title_el = card.select_one(".card-property__title")187        title = title_el.get_text(strip=True) if title_el else slug188        addr_el = card.select_one(".card-property__address--text")189        address = addr_el.get_text(" ", strip=True) if addr_el else ""190191        # « 7615 Rue des Métis, Quebec, QC » -> ville = avant-dernier segment192        parts = [p.strip() for p in address.split(",") if p.strip()]193        city = parts[-2] if len(parts) >= 2 else ""194        city = _CITY_CANON.get(_city_key(city), city) or "Québec"195196        rate_el = card.select_one(".card-property__rate-min")197        beds_el = card.select_one(".card-property__beds-text")198        card_sig = (f"{address}|{rate_el.get_text(strip=True) if rate_el else ''}"199                    f"|{beds_el.get_text(strip=True) if beds_el else ''}")200201        # page immeuble (cache BD, invalidée quand la carte liste change)202        key = hashlib.sha1(card_sig.encode("utf-8")).hexdigest()203204        def fetch_fn():205            if self._fetched >= self.max_details:206                raise RuntimeError("budget de pages immeuble atteint")207            self._fetched += 1208            return self._fetch_building(url)209210        payload = self.detail(slug, key, fetch_fn)211        if not payload:212            return []213214        building_addr = payload.get("address") or address215        details_base: dict = {"building": title}216        if payload.get("phone"):217            details_base["contact"] = {"phone": payload["phone"]}218219        out: list[Listing] = []220        for u in payload.get("units", []):221            numero = u.get("unit") or ""222            if not numero:223                continue224            amenities = list(payload.get("amenities", []))225            if u.get("bed"):226                amenities.insert(0, f"{u['bed']} chambre(s)")227            if u.get("bath"):228                amenities.insert(1, f"{u['bath']} salle(s) de bain")229230            area = None231            sqft = re.sub(r"[\s,  ]", "", u.get("sqft") or "")232            if re.fullmatch(r"\d{2,5}", sqft) and 80 <= float(sqft) <= 20000:233                area = float(sqft)234235            details = dict(details_base)236            if u.get("floorplan"):237                details["floorplan"] = u["floorplan"]238239            out.append(Listing(240                source=self.source_id,241                external_id=f"{slug}--{numero}",242                url=url,243                title=f"{title} — unité {numero}",244                address=building_addr,245                city=city,246                unit_type=_unit_type(u.get("bed", "")),247                price=parse_price(u.get("rate", "")),248                price_label=u.get("rate", ""),249                availability=u.get("availability", ""),250                area_sqft=area,251                description=payload.get("description", ""),252                amenities=amenities,253                details=details,254                images=(u.get("photos") or payload.get("gallery") or [])[:20],255            ))256        return out257258    # -- page immeuble ------------------------------------------------------------259    def _fetch_building(self, url: str) -> dict:260        """Payload JSON-sérialisable : unités disponibles + infos immeuble."""261        resp = self.get(url)262        resp.encoding = "utf-8"              # charset absent des en-têtes263        html = resp.text264        soup = BeautifulSoup(html, "html.parser")265        payload: dict = {}266267        # adresse de la bannière (identique à la liste, sans code postal)268        addr = soup.select_one(".banner-property__address--text")269        if addr:270            payload["address"] = addr.get_text(" ", strip=True)271272        # description « À propos de la propriété »273        desc = soup.select_one(".property-about__content")274        if desc:275            payload["description"] = re.sub(276                r"\s+", " ", desc.get_text(" ", strip=True)).strip()[:1200]277278        # commodités : immeuble + unité (blocs dupliqués desktop/mobile)279        amenities: list[str] = []280        for li in soup.select(".amenities-default li"):281            t = re.sub(r"\s+", " ", li.get_text(" ", strip=True))282            if t and t not in amenities:283                amenities.append(t)284        payload["amenities"] = amenities285286        # téléphone de l'immeuble (liens tel:, en excluant le siège social)287        for a in soup.select('a[href^="tel:"]'):288            digits = re.sub(r"\D", "", a["href"])289            if len(digits) >= 10 and digits[-10:] != _CORPORATE_PHONE:290                d = digits[-10:]291                payload["phone"] = f"{d[:3]}-{d[3:6]}-{d[6:]}"292                break293294        # galerie de l'immeuble : préférer la variante /1152/, dédupliquer295        gallery: list[str] = []296        seen: set[str] = set()297        urls = re.findall(298            r"https://s3\.amazonaws\.com/lws_lift/girescom/images/gallery/[^\"'\s]+",299            html)300        for u in urls:301            fname = u.rsplit("/", 1)[-1]302            if fname in seen:303                continue304            big = u.replace("/512/", "/1152/")305            if big in urls or big == u:306                seen.add(fname)307                gallery.append(big if big in urls else u)308        payload["gallery"] = gallery[:20]309310        # tableau des unités disponibles (colonnes structurées column-field)311        units: list[dict] = []312        for row in soup.select("li.unit-table-desktop__units--unit"):313            cols = {li.get("column-field"): li314                    for li in row.select("li[column-field]")}315316            def txt(field: str) -> str:317                el = cols.get(field)318                return re.sub(r"\s+", " ", el.get_text(" ", strip=True)) if el else ""319320            unit = {321                "unit": txt("typeName"),322                "bed": txt("bed"),323                "bath": txt("bath"),324                "rate": txt("rate"),325                "sqft": txt("sqFt"),326                "availability": txt("availability"),327            }328            photos_el = cols.get("photos")329            if photos_el:330                unit["photos"] = list(dict.fromkeys(331                    a["href"] for a in photos_el.select("a[href^='http']")))332            plan_el = cols.get("floorplans")333            if plan_el:334                plan = plan_el.select_one("a[href^='http']")335                if plan:336                    unit["floorplan"] = plan["href"]337            if unit["unit"] and unit["unit"] != "-":338                units.append(unit)339        payload["units"] = units340        return payload341
Files main
Menu

Theme