SPB Git

Repository Public

hestia.py 10.0 KB 242 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/hestia.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/hestia.py : connecteur Hestia Groupe immobilier (gestionhestia.com)91#   WordPress Elementor, CPT « apartments » non exposé en REST : la page92#   /location/ liste des cartes <article class="apartment-single"> (type,93#   secteur, prix/mois, photo, lien fiche). Les fiches détail (cache BD)94#   ajoutent titre, adresse civique complète, description, caractéristiques95#   (dont « Animaux interdits »), services de proximité et galerie.96# -----------------------------------------------------------------------------97from __future__ import annotations9899import hashlib100import re101102from bs4 import BeautifulSoup103104from ..schema import Listing, normalize_unit_type, parse_price, strip_accents105from .base import BaseConnector106107BASE = "https://www.gestionhestia.com"108LIST_URL = f"{BASE}/location/"109110_BG_URL_RE = re.compile(r"url\((['\"]?)(https?://[^)'\"]+)\1\)")111112113def _pets_from_amenities(amenities: list[str]) -> str | None:114    """« Animaux interdits » / « Animaux acceptés » (caractéristique structurée)."""115    for a in amenities:116        k = strip_accents(a.lower())117        if "animaux" in k or "animal" in k:118            if "interdit" in k or "refus" in k:119                return "non"120            if "accept" in k or "permis" in k:121                return "oui"122    return None123124125class HestiaConnector(BaseConnector):126    source_id = "hestia"127    request_delay = 0.7128    max_details = 40    # garde-fou fiches détail (vraies requêtes)129130    def fetch(self) -> list[Listing]:131        html = self.get(LIST_URL).text132        soup = BeautifulSoup(html, "html.parser")133134        listings: dict[str, Listing] = {}135        for a in soup.select("ul.apartments a[href*='/apartments/']"):136            art = a.find("article", class_="apartment-single")137            if art is None:138                continue139            url = a["href"]140            m = re.search(r"/apartments/([^/]+)/?", url)141            if not m:142                continue143            ext_id = m.group(1)              # slug WP du CPT « apartments »144            if ext_id in listings:145                continue146            rooms_el = art.select_one(".apartment-single__rooms")147            rooms = rooms_el.get_text(" ", strip=True) if rooms_el else ""148            if re.search(r"commercial|stationnement|rangement|chambre",149                         rooms + " " + ext_id, re.I):150                continue151            sector_el = art.select_one(".apartment-single__sector")152            sector = sector_el.get_text(" ", strip=True) if sector_el else ""153            price_el = art.select_one(".apartment-single__price")154            price_label = re.sub(r"\s+", " ", price_el.get_text(" ", strip=True)) if price_el else ""155156            images: list[str] = []157            img_el = art.select_one(".apartment-single__img[style]")158            if img_el:159                mm = _BG_URL_RE.search(img_el["style"])160                if mm:161                    images.append(mm.group(2))162163            listings[ext_id] = Listing(164                source=self.source_id,165                external_id=ext_id,166                url=url,167                title=rooms,                       # remplacé par le titre de la fiche168                # tout le parc Hestia (Domaine Cartier, Boisé Nature 3R) est à169                # Trois-Rivières ; l'adresse de la fiche confirme/écrase170                city=sector or "Trois-Rivières",171                unit_type=normalize_unit_type(rooms),172                price=parse_price(price_label),173                price_label=price_label,174                images=images,175            )176177        # Fiches détail (cache BD) : titre, adresse, description,178        # caractéristiques + services, galerie complète179        self._fetched = 0180        for lst in listings.values():181            card_key = hashlib.sha1(182                f"{lst.title}|{lst.price_label}|{lst.url}".encode("utf-8")183            ).hexdigest()184            try:185                payload = self.detail(lst.external_id, card_key,186                                      lambda u=lst.url: self._fetch_detail(u))187            except Exception:188                continue189            self._apply_detail(lst, payload)190        return list(listings.values())191192    # -- fiche détail --------------------------------------------------------193    def _fetch_detail(self, url: str) -> dict:194        if self._fetched >= self.max_details:195            raise RuntimeError("budget de fiches détail atteint")196        self._fetched += 1197        soup = BeautifulSoup(self.get(url).text, "html.parser")198        out: dict = {}199200        title_el = soup.select_one(".apartment__title")201        if title_el:202            out["title"] = re.sub(r"\s+", " ", title_el.get_text(" ", strip=True))203        addr_el = soup.select_one("address.apartment__address")204        if addr_el:205            out["address"] = re.sub(r"\s+", " ", addr_el.get_text(" ", strip=True))206        desc_el = soup.select_one(".apartment__description")207        if desc_el:208            out["description"] = desc_el.get_text("\n", strip=True)[:1200]209        # onglets « Caractéristiques » / « Services de proximité »210        out["amenities"] = [li.get_text(" ", strip=True)211                            for li in soup.select(".tabs .tabs__content li")212                            if li.get_text(strip=True)][:40]213        out["images"] = []214        for img in soup.select(".apartment__gallery img[src]"):215            src = img["src"]216            if src.startswith("http") and src not in out["images"]:217                out["images"].append(src)218        out["images"] = out["images"][:30]219        return out220221    def _apply_detail(self, lst: Listing, d: dict) -> None:222        if not d:223            return224        if d.get("title"):225            lst.title = d["title"]226        addr = d.get("address", "")227        if addr:228            # « 6005 rue de la Mattawin, Trois-Rivières, QC G8Y 0M8, Canada »229            parts = [p.strip() for p in addr.split(",") if p.strip()]230            lst.address = parts[0] if parts else addr231            if len(parts) >= 2 and not re.match(r"(?i)qc|q[ué]ebec|canada|[A-Z]\d[A-Z]", parts[1]):232                lst.city = parts[1]233        if d.get("description"):234            lst.description = d["description"]235        if d.get("amenities"):236            lst.amenities = list(dict.fromkeys(lst.amenities + d["amenities"]))237            pets = _pets_from_amenities(d["amenities"])238            if pets:239                lst.pets = pets240        if d.get("images"):241            lst.images = list(dict.fromkeys(d["images"] + lst.images))[:30]242
Files main
Menu

Theme