SPB Git

Repository Public

elite.py 9.5 KB 241 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/elite.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-0913# 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/elite.py : connecteur Elite Immobilier (eliteimmobilier.ca — Gatineau)91#   Gestionnaire de projets locatifs neufs à Gatineau (Complexe Fraser à92#   Aylmer, Desrosiers rue Larabie, Nuvo au Plateau). WordPress/Elementor :93#   le hub /trouver-un-logement/ liste une page par projet, découverte à94#   chaque sync. Chaque page projet publie ses typologies avec prix dans des95#   boutons Elementor (« 1 CHAMBRE À PARTIR DE $1499/MOIS* ») -> une annonce96#   par typologie affichée AVEC prix. Le portail SecureCafe (Yardi) du site97#   est réservé aux résidents : aucune unité individuelle publique — la98#   granularité typologie est donc la donnée la plus fine disponible.99#   Adresses/secteurs : publiés en clair sur chaque page projet ; un mapping100#   des slugs connus fournit l'adresse vérifiée (jamais devinée pour un slug101#   inconnu -> address vide).102# -----------------------------------------------------------------------------103from __future__ import annotations104105import re106from urllib.parse import urljoin107108from bs4 import BeautifulSoup109110from ..schema import Listing, normalize_unit_type, parse_price, strip_accents111from .base import BaseConnector112113BASE = "https://eliteimmobilier.ca"114HUB_URL = f"{BASE}/trouver-un-logement/"115116# métadonnées vérifiées à la main (2026-08) — les slugs inconnus passent117# quand même, avec adresse/secteur vides plutôt qu'inventés118KNOWN = {119    "complexe-chemin-fraser": {120        "name": "Complexe Fraser",121        "address": "475-515, chemin Fraser, Gatineau", "sector": "Aylmer"},122    "desrosiers-rue-larabie": {123        "name": "Desrosiers",124        "address": "176, rue Larabie, Gatineau", "sector": ""},125    "projet-nuvo-plateau": {126        "name": "Nuvo",127        "address": "699, boulevard du Plateau, Gatineau", "sector": "Plateau"},128}129130# « 1 CHAMBRE À PARTIR DE $1499/MOIS* » / « STUDIO À PARTIR DE $1399/MOIS* »131_TYPO_RE = re.compile(132    r"^\s*(.{2,40}?)\s*[ÀA]\s+PARTIR\s+DE\s*\$?\s*([\d\s,.]+)\s*/\s*MOIS",133    re.I)134_IMG_RE = re.compile(135    r'https?://[^"\'\s\)]+/wp-content/uploads/[^"\'\s\)]+\.(?:jpg|jpeg|webp|png)',136    re.I)137_SKIP_IMG = re.compile(r"logo|icon|favicon|cropped|-\d{2,4}x\d{2,4}\.", re.I)138139140def _slugify(s: str) -> str:141    s = strip_accents(s.lower())142    return re.sub(r"[^a-z0-9]+", "-", s).strip("-")143144145class EliteConnector(BaseConnector):146    source_id = "elite"147    request_delay = 1.0148    max_projects = 12149    max_images = 10150151    # -- typologie -> type d'unité ------------------------------------------------152    @staticmethod153    def _unit_type(label: str) -> str:154        t = strip_accents(label.lower())155        if "studio" in t:156            return "Studio"157        m = re.match(r"^(\d+)\s*ch", t)158        if m:159            return normalize_unit_type(f"{m.group(1)} chambres")160        return normalize_unit_type(label)161162    # -- page projet ----------------------------------------------------------163    def _parse_project(self, url: str, listings: list[Listing]) -> None:164        html = self.get(url).text165        soup = BeautifulSoup(html, "html.parser")166        slug = url.rstrip("/").rsplit("/", 1)[-1]167        meta = KNOWN.get(slug, {})168169        h1 = soup.find("h1")170        page_title = h1.get_text(" ", strip=True) if h1 else slug171        name = meta.get("name") or page_title.split(":")[0].strip()172173        # description marketing du projet (og:description rédigé par l'agence)174        og = soup.find("meta", attrs={"property": "og:description"})175        blurb = (og.get("content", "").strip() if og else "")[:600]176177        # « Emménagez dès le 1er juillet » / « EMMÉNAGER À PARTIR DÈS MAINTENANT »178        text = soup.get_text("\n", strip=True)179        availability = ""180        m = re.search(r"(?i)emm[ée]nage[rz]?[^\n.!]{0,60}", text)181        if m:182            availability = re.sub(r"\s+", " ", m.group(0)).strip(" :*")183184        images: list[str] = []185        for u in dict.fromkeys(_IMG_RE.findall(html)):186            if not _SKIP_IMG.search(u) and u not in images:187                images.append(u)188189        # boutons de typologie avec prix (donnée la plus fine publiée)190        seen: set[str] = set()191        for btn in soup.select("span.elementor-button-text"):192            raw = re.sub(r"\s+", " ", btn.get_text(" ", strip=True)).strip()193            m = _TYPO_RE.match(raw)194            if not m:195                continue196            typo = m.group(1).strip(" -–")197            key = _slugify(typo)198            if not key or key in seen:199                continue200            seen.add(key)201            price_label = raw.rstrip("*")202            listings.append(Listing(203                source=self.source_id,204                external_id=f"{slug}:{key}",205                url=url,206                title=f"{name} — {typo.title()}",207                address=meta.get("address", ""),208                sector=meta.get("sector", ""),209                city="Gatineau",210                unit_type=self._unit_type(typo),211                price=parse_price(price_label),212                price_label=price_label,213                availability=availability,214                description=blurb,215                images=images[: self.max_images],216            ))217218    # -- fetch -----------------------------------------------------------------219    def fetch(self) -> list[Listing]:220        html = self.get(HUB_URL).text221        soup = BeautifulSoup(html, "html.parser")222        urls: list[str] = []223        for a in soup.select("a[href*='/trouver-un-logement/']"):224            u = urljoin(BASE, a["href"]).split("#")[0].split("?")[0]225            if not u.endswith("/"):226                u += "/"227            if u != HUB_URL and "/en/" not in u and u not in urls:228                urls.append(u)229230        listings: list[Listing] = []231        for url in urls[: self.max_projects]:232            try:233                self._parse_project(url, listings)234            except Exception:235                continue236237        uniq: dict[str, Listing] = {}238        for lst in listings:239            uniq.setdefault(lst.external_id, lst)240        return list(uniq.values())241
Files main
Menu

Theme