SPB Git

Repository Public

cap_gestion.py 14.0 KB 327 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/cap_gestion.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/cap_gestion.py : connecteur CAP Gestion / CAP Immobilier91#   (capgestion.ca) — Saint-Jérôme, Lachute, Mirabel, Joliette, Louiseville,92#   Repentigny, Lavaltrie, Brownsburg-Chatham…93#   WordPress + plugin immobilier Estatik 4 Pro : la page « Logements à94#   louer » (rendu serveur, ~10 fiches/page, pagination ?paged-1=N) expose95#   des cartes .es-listing avec data-post-id (id STABLE), prix, adresse96#   complète et type de logement. Chaque fiche /propriete/<slug>/ fournit97#   les champs STRUCTURÉS Estatik (.es-property-field : type, salles de98#   bain, chambres, superficie, animaux, chauffage, stationnement, étage,99#   période de location…) + description et galerie.100#   Les fiches étiquetées « Loué » (es_label/loue) sont exclues : le101#   logement n'est plus offert. robots.txt permissif (Yoast).102# -----------------------------------------------------------------------------103from __future__ import annotations104105import hashlib106import json107import re108109from bs4 import BeautifulSoup110111from ..schema import Listing, parse_price112from .base import BaseConnector113114BASE = "https://capgestion.ca"115LIST_URL = f"{BASE}/gestion-immobiliere-logements-a-louer/"116117# adresse Estatik : « 412 Av. Barron, Lachute, QC J8H 0W2, Canada »118# (la ville est la composante qui précède « QC » ; certaines fiches omettent119# la province — on prend alors la dernière composante non postale)120_QC_RE = re.compile(r"^(?:QC|Qc|Québec|Quebec)\b", re.I)121_POSTAL_RE = re.compile(r"[A-Z]\d[A-Z]\s*\d[A-Z]\d", re.I)122# le site écrit tantôt « Brownsburg », tantôt « Brownsburg-Chatham »123# (même municipalité) : canonicalisation factuelle124_CITY_FIX = {"Brownsburg": "Brownsburg-Chatham"}125126127def _city_from_address(address: str) -> str:128    parts = [p.strip() for p in address.split(",") if p.strip()]129    for i, p in enumerate(parts):130        if _QC_RE.match(p) and i > 0:131            return _CITY_FIX.get(parts[i - 1], parts[i - 1])132    # pas de « QC » : dernière composante non postale/pays (ex.133    # « 181 de la Scierie, Brownsburg-Chatham »)134    for p in reversed(parts[1:]):135        if p.lower() == "canada" or _POSTAL_RE.search(p) or re.search(r"\d", p):136            continue137        return _CITY_FIX.get(p, p)138    return ""139# images de la galerie (uploads WordPress), variantes redimensionnées exclues140_IMG_RE = re.compile(141    r"https://capgestion\.ca/wp-content/uploads/[^\"'\s\)]+\.(?:jpe?g|png|webp)",142    re.I)143_SKIP_IMG = re.compile(r"logo|icon|favicon|-\d{2,3}x\d{2,3}\.", re.I)144145146class _CapAtteint(Exception):147    """Plafond de requêtes détail atteint pour cette synchronisation."""148149150class CapGestionConnector(BaseConnector):151    source_id = "cap_gestion"152    request_delay = 0.7153    max_list_pages = 25          # garde-fou (13 pages observées)154    max_real_details = 60        # vraies requêtes fiches par sync (cache exclu)155156    # -- liste --------------------------------------------------------------------157    def _parse_page(self, html: str, cards: dict[str, dict]) -> int:158        """Cartes es-listing d'une page ; retourne le nombre total de pages."""159        soup = BeautifulSoup(html, "html.parser")160        for el in soup.select(".js-es-listing[data-post-id]"):161            pid = el.get("data-post-id", "").strip()162            if not pid or pid in cards:163                continue164            labels = [a.get_text(" ", strip=True)165                      for a in el.select(".es-badges a")]166            link = el.select_one("a.es-listings__image__link") or \167                el.select_one(".es-listing__body a[href]") or \168                el.find("a", href=re.compile(r"/propriete/|/property/"))169            url = (link.get("href") or "") if link else ""170            title_el = el.select_one(".es-listing__title, h3 a, h2 a")171            title = title_el.get_text(" ", strip=True) if title_el else ""172            addr_el = el.select_one(".es-address")173            address = addr_el.get_text(" ", strip=True) if addr_el else ""174            price_el = el.select_one(".es-price")175            price_label = price_el.get_text(" ", strip=True) if price_el else ""176            badge = el.select_one(".es-badge--normal")177            if badge:                       # ex. « Par mois »178                price_label = f"{price_label} {badge.get_text(strip=True)}".strip()179            unit_el = el.select_one(".es-listing__meta-types-de-logement")180            unit_type = unit_el.get_text(" ", strip=True) if unit_el else ""181            imgs = []182            for im in el.select(".es-listing__image img"):183                u = im.get("data-lazy") or im.get("src") or ""184                if u.startswith("http") and u not in imgs:185                    imgs.append(u)186            cards[pid] = {187                "url": url, "title": title, "address": address,188                "price_label": price_label, "unit_type": unit_type,189                "labels": labels, "images": imgs,190            }191        # pagination : « 1 - 10 of 124 properties » + liens ?paged-1=N192        pages = 1193        for a in soup.select(".js-es-pagination a.page-numbers"):194            m = re.search(r"paged-1=(\d+)", a.get("href") or "")195            if m:196                pages = max(pages, int(m.group(1)))197        return pages198199    # -- fiche (champs structurés Estatik) ------------------------------------------200    def _unit_detail(self, pid: str, url: str, key: str) -> dict:201        def _fetch() -> dict:202            if self._real_details >= self.max_real_details:203                raise _CapAtteint()204            self._real_details += 1205            html = self.get(url).text206            soup = BeautifulSoup(html, "html.parser")207            out: dict = {"fields": {}}208            for f in soup.select(".es-property-field"):209                label_el = f.select_one(".es-property-field__label")210                value_el = f.select_one(".es-property-field__value")211                if label_el is None or value_el is None:212                    txt = f.get_text(" ", strip=True)213                    if ":" in txt:214                        lab, _, val = txt.partition(":")215                    else:216                        continue217                else:218                    lab = label_el.get_text(" ", strip=True)219                    val = value_el.get_text(" ", strip=True)220                lab = re.sub(r"\s*:\s*$", "", re.sub(r"\s+", " ", lab)).strip()221                val = re.sub(r"\s+", " ", val).strip()222                if lab and val:223                    out["fields"][lab] = val224            imgs = [u for u in dict.fromkeys(_IMG_RE.findall(html))225                    if not _SKIP_IMG.search(u)]226            out["images"] = imgs[:20]227            return out228229        try:230            return self.detail(pid, key, _fetch)231        except Exception:232            return {}233234    # -- fetch --------------------------------------------------------------------235    def fetch(self) -> list[Listing]:236        self._real_details = 0237        cards: dict[str, dict] = {}238239        pages = self._parse_page(self.get(LIST_URL).text, cards)240        for n in range(2, min(pages, self.max_list_pages) + 1):241            try:242                self._parse_page(243                    self.get(LIST_URL, params={"paged-1": n}).text, cards)244            except Exception:245                continue246247        listings: list[Listing] = []248        for pid, c in cards.items():249            if "Loué" in c["labels"]:      # plus disponible : exclu250                continue251            if not c["url"].startswith("http"):252                continue253            key = hashlib.sha1(json.dumps(c, sort_keys=True, ensure_ascii=False)254                               .encode("utf-8")).hexdigest()[:16]255            det = self._unit_detail(pid, c["url"], key)256            fields = det.get("fields") or {}257258            # ville : composante de l'adresse Estatik (structurée)259            city = _city_from_address(c["address"])260261            unit_type = fields.get("Type de logement") or c["unit_type"]262            desc = fields.get("La description") or ""263            area = None264            try:265                v = float(str(fields.get("Superficie", "")).replace(",", "")266                          .replace(" ", ""))267                if 80 <= v <= 20000:268                    area = v269            except ValueError:270                pass271272            details: dict = {}273            beds = fields.get("Chambres totales")274            if beds and beds.isdigit():275                details["bedrooms"] = int(beds)276            baths = fields.get("Salle(s) de bain")277            if baths and baths.isdigit():278                details["bathrooms"] = int(baths)279            if fields.get("Étage"):280                details["floor_label"] = fields["Étage"]281            if fields.get("Période de location"):282                details["lease"] = fields["Période de location"]283284            pets = None285            pets_raw = fields.get("Animaux acceptés", "")286            if re.search(r"non|aucun|interdit", pets_raw, re.I):287                pets = "non"288            elif pets_raw:289                pets = "conditions" if re.search(290                    r"frais|maximum|condition|stéril", pets_raw, re.I) else "oui"291292            amenities = []293            for lab in ("Animaux acceptés", "Type d'animal autorisé",294                        "Électros inclus", "Chauffage et électricité",295                        "Nb de stationnements", "Type de stationnement",296                        "Enquête de prélocation complète"):297                if fields.get(lab):298                    amenities.append(f"{lab} : {fields[lab]}")299300            # disponibilité : uniquement si affichée (souvent dans le titre,301            # ex. « … – 1ER AOÛT » ou « Disponible maintenant ») — rien d'inventé302            availability = ""303            m = re.search(r"Disponible[^.|]*", desc, re.I)304            if m:305                availability = m.group(0).strip()306307            listings.append(Listing(308                source=self.source_id,309                external_id=pid,310                url=c["url"],311                title=c["title"],312                address=c["address"],313                sector="",314                city=city,315                unit_type=unit_type,316                price=parse_price(c["price_label"]),317                price_label=c["price_label"],318                availability=availability,319                area_sqft=area,320                pets=pets,321                description=desc[:600],322                amenities=amenities,323                details=details,324                images=(det.get("images") or c["images"])[:20],325            ))326        return listings327
Files main
Menu

Theme