SPB Git

Repository Public

gestion_laprise.py 11.2 KB 283 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/gestion_laprise.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/gestion_laprise.py : connecteur Gestion Laprise91#   (gestionlaprise.com/immobilier — Baie-Comeau et Haute-Côte-Nord, ~7092#   appartements, location 31 jours et plus). WordPress + thème Inspiry Real93#   Places (plugin inspiry-real-estate), tout rendu serveur. Archive94#   /logement-statut/a-louer/ (paginée) : cartes `article.property-listing-simple`95#   — titre, adresse complète, prix (« $850 Par mois »), meta Bedrooms/96#   Bathrooms/Type (1½–6½)/Status. Fiche /propriete/<immeuble>/<unité>/ (via97#   cache BD) : description, caractéristiques, GPS (propertyMapData) et galerie98#   pleine taille (envira-gallery) — le carrousel « propriétés similaires »99#   (owl-carousel) est ignoré. Unités hôtelières (statut « Hôtel ») et locaux100#   commerciaux exclus. Pas de robots.txt (= tout permis).101# -----------------------------------------------------------------------------102from __future__ import annotations103104import hashlib105import json106import re107108from bs4 import BeautifulSoup109110from ..schema import Listing, normalize_unit_type, parse_price111from .base import BaseConnector112113BASE = "https://gestionlaprise.com/immobilier"114LIST_URL = f"{BASE}/logement-statut/a-louer/"115MAX_PAGES = 8116117_MAP_DATA_RE = re.compile(r"propertyMapData\s*=\s*(\{.*?\});", re.S)118119120def _clean_price_label(label: str) -> str:121    """'$1,050 Par mois' -> '$1050 Par mois' compatible parse_price."""122    return re.sub(r"(\d),(\d{3})", r"\1\2", label)123124125class GestionLapriseConnector(BaseConnector):126    source_id = "gestion_laprise"127    request_delay = 0.6128    max_details = 30     # garde-fou fiches détail (vraies requêtes par sync)129130    def fetch(self) -> list[Listing]:131        self._fetched = 0132        listings: dict[str, Listing] = {}133        for page in range(1, MAX_PAGES + 1):134            url = LIST_URL if page == 1 else f"{LIST_URL}page/{page}/"135            try:136                html = self.get(url).text137            except Exception:138                break                      # /page/N/ inexistante -> 404, fin139            soup = BeautifulSoup(html, "html.parser")140            cards = soup.select("article.property-listing-simple")141            if not cards:142                break143            for card in cards:144                try:145                    self._parse_card(card, listings)146                except Exception:147                    continue148        return list(listings.values())149150    # -- carte (archive Inspiry Real Places) -------------------------------------151    def _parse_card(self, card, listings: dict[str, Listing]) -> None:152        link = card.select_one('h3.entry-title a[href*="/propriete/"]')153        if not link:154            return155        url = link["href"]156        title = link.get_text(strip=True)157        m = re.search(r"/propriete/([^/?#]+)/([^/?#]+)", url)158        if not m:159            return160        ext_id = f"{m.group(1)}--{m.group(2)}"161        if ext_id in listings:162            return163164        # meta structurée : Bedrooms / Bathrooms / Type / Status165        meta: dict[str, str] = {}166        for item in card.select(".property-meta .meta-item"):167            label = item.select_one(".meta-item-label")168            value = item.select_one(".meta-item-value")169            if label and value:170                meta[label.get_text(strip=True).lower()] = value.get_text(strip=True)171        unit_label = meta.get("type", "")172        status = meta.get("status", "")173174        # exclusions : unités hôtelières (nuitée) et locaux commerciaux175        if re.search(r"h[oô]tel", f"{status} {title}", re.I):176            return177        if re.search(r"local|commercial|bureau", unit_label, re.I):178            return179180        addr_el = card.select_one("p.property-address")181        address = re.sub(r"\s+", " ",182                         addr_el.get_text(" ", strip=True)) if addr_el else ""183        # ville : « 112 Avenue le Gardeur, Baie-Comeau, QC G4Z 1H8, Canada »184        city = ""185        parts = [p.strip() for p in address.split(",")]186        if len(parts) >= 3:187            city = parts[-3]188189        price_el = card.select_one(".price-wrapper .price")190        postfix_el = card.select_one(".price-wrapper .postfix-text")191        price_label = price_el.get_text(strip=True) if price_el else ""192        if price_label and postfix_el and postfix_el.get_text(strip=True):193            price_label += f" {postfix_el.get_text(strip=True)}"194195        amenities: list[str] = []196        if meta.get("bedrooms"):197            amenities.append(f"{meta['bedrooms']} chambre(s)")198        if meta.get("bathrooms"):199            amenities.append(f"{meta['bathrooms']} salle(s) de bain")200201        images: list[str] = []202        thumb = card.select_one(".property-thumbnail img[src]")203        if thumb:204            images.append(thumb["src"])205206        lst = Listing(207            source=self.source_id,208            external_id=ext_id,209            url=url,210            title=title,211            address=address,212            city=city,213            unit_type=normalize_unit_type(unit_label),214            price=parse_price(_clean_price_label(price_label)),215            price_label=price_label,216            availability=status,           # « À Louer » (statut brut du site)217            amenities=amenities,218            images=images,219        )220221        key = hashlib.sha1(222            f"{title}|{price_label}|{status}|{unit_label}".encode("utf-8")223        ).hexdigest()224        try:225            payload = self.detail(ext_id, key, lambda u=url: self._fetch_detail(u))226            self._apply_detail(lst, payload)227        except Exception:228            pass229        listings[ext_id] = lst230231    # -- fiche détail (/propriete/<immeuble>/<unité>/) ------------------------------232    def _fetch_detail(self, url: str) -> dict:233        """Description, caractéristiques, GPS et galerie envira pleine taille."""234        if self._fetched >= self.max_details:235            raise RuntimeError("budget de fiches détail atteint")236        self._fetched += 1237        html = self.get(url).text238        soup = BeautifulSoup(html, "html.parser")239        out: dict = {}240241        desc_el = soup.select_one(".entry-content")242        if desc_el:243            txt = desc_el.get_text("\n", strip=True)244            txt = re.sub(r"^Description\n?", "", txt)245            out["description"] = re.sub(r"[ \t]+", " ", txt).strip()[:1500]246247        out["features"] = [248            re.sub(r"\s+", " ", li.get_text(" ", strip=True))249            for li in soup.select(".property-features li")250            if li.get_text(strip=True)][:20]251252        # GPS : propertyMapData = {"lat":"49.23...","lang":"-68.15..."}253        m = _MAP_DATA_RE.search(html)254        if m:255            try:256                data = json.loads(m.group(1))257                out["lat"] = float(data.get("lat"))258                out["lng"] = float(data.get("lang"))259            except (TypeError, ValueError):260                pass261262        # galerie envira : liens vers les images pleine taille (« -scaled »)263        images: list[str] = []264        for a in soup.select('.envira-gallery-wrap a[href*="/uploads/"]'):265            u = a["href"]266            if u.startswith("http") and u not in images:267                images.append(u)268        out["images"] = images[:25]269        return out270271    def _apply_detail(self, lst: Listing, d: dict) -> None:272        """Reporte le payload (frais ou en cache) sur l'annonce."""273        if not d:274            return275        if d.get("description"):276            lst.description = d["description"]277        if d.get("features"):278            lst.amenities = list(dict.fromkeys(lst.amenities + d["features"]))279        if d.get("lat") is not None and d.get("lng") is not None:280            lst.lat, lst.lng = d["lat"], d["lng"]281        if d.get("images") and len(d["images"]) > len(lst.images):282            lst.images = d["images"]283
Files main
Menu

Theme