SPB Git

Repository Public

stb_immobilier.py 11.2 KB 279 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/stb_immobilier.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/stb_immobilier.py : connecteur STB Immobilier (stbimmobilier.com)91#   Gestionnaire de Matane (Bas-Saint-Laurent) : ~11 immeubles/projets à Matane92#   et Saint-Ulric (rue Fournier, Boisé St-Rédempteur, rue Marquis, maisons de93#   ville…). WordPress + Elementor, tout rendu serveur. Liste94#   /locations-residentielles/ : cartes `e-loop-item` par IMMEUBLE (granularité95#   immeuble — le site ne publie pas d'unités individuelles) : nombre de96#   logements/maisons, adresse civique avec ville, nom, « Unités en location »97#   (typologies réelles « 4 X 4 ½, 6 X 5 ½ »), « À partir de X $/mois » et98#   parfois « Date de disponibilité ». Fiche /location/<slug>/ (via cache BD) :99#   type de location, services associés/à proximité, photos.100#   robots.txt ouvert, sitemap Yoast.101# -----------------------------------------------------------------------------102from __future__ import annotations103104import hashlib105import re106107from bs4 import BeautifulSoup108109from ..schema import Listing, normalize_unit_type, parse_price110from .base import BaseConnector111112BASE = "https://stbimmobilier.com"113LIST_URL = f"{BASE}/locations-residentielles/"114115_PRICE_RE = re.compile(r"À partir de[\s ]*([\d\s .,]+\$\s*/\s*mois)", re.I)116_DISPO_RE = re.compile(117    r"Date de disponibilité\s*:\s*(.+?)(?=Unités en location|Type de location|À partir de|$)",118    re.I | re.S)119_UNITES_RE = re.compile(120    r"(?:Unités en location|Type de location)\s*:\s*(.+?)(?=À partir de|$)",121    re.I | re.S)122_TYPE_RE = re.compile(r"(\d\s*½|Studio|Loft|maisons? de ville)", re.I)123124125class STBImmobilierConnector(BaseConnector):126    source_id = "stb_immobilier"127    request_delay = 0.6128    max_details = 15     # garde-fou fiches détail (vraies requêtes par sync)129130    def fetch(self) -> list[Listing]:131        html = self.get(LIST_URL).text132        soup = BeautifulSoup(html, "html.parser")133134        self._fetched = 0135        listings: dict[str, Listing] = {}136        for card in soup.select("div.e-loop-item"):137            try:138                self._parse_card(card, listings)139            except Exception:140                continue141        return list(listings.values())142143    # -- carte immeuble (boucle Elementor) ------------------------------------------144    def _parse_card(self, card, listings: dict[str, Listing]) -> None:145        link = card.select_one('a[href*="/location/"]')146        if not link:147            return148        url = link["href"]149        m = re.search(r"/location/([^/?#]+)", url)150        if not m:151            return152        ext_id = m.group(1)153        if ext_id in listings:154            return155156        # entêtes : [nombre, « logements|maisons », adresse, nom de l'immeuble]157        # (widgets « heading » Elementor — balises variables, pas toujours h1-h6)158        heads = [re.sub(r"\s+", " ", h.get_text(" ", strip=True))159                 for h in card.select(".elementor-widget-heading")]160        count = kind = address = name = ""161        for h in heads:162            if re.search(r"(?i)unités en location|type de location"163                         r"|date de disponibilité|à partir de", h):164                continue                      # lignes d'infos, traitées plus bas165            if re.fullmatch(r"\d+", h):166                count = h167            elif re.fullmatch(r"(logements?|maisons?)", h, re.I):168                kind = h.lower()169            elif "," in h:170                address = h171            elif h:172                name = h173174        city = ""175        parts = [p.strip() for p in address.split(",") if p.strip()]176        if parts:177            city = re.sub(r"\s+", " ", parts[-1]).strip()178179        # texte de la carte : disponibilité, typologies, prix « À partir de »180        text = re.sub(r"\s+", " ", card.get_text(" ", strip=True))181        m_d = _DISPO_RE.search(text)182        availability = m_d.group(1).strip(" .|") if m_d else ""183        m_u = _UNITES_RE.search(text)184        unites = m_u.group(1).strip(" .|") if m_u else ""185        m_p = _PRICE_RE.search(text)186        price_label = f"À partir de {m_p.group(1).strip()}" if m_p else ""187188        # type d'unité : seulement si l'immeuble n'offre qu'une typologie189        unit_type = ""190        types = {normalize_unit_type(re.sub(r"(?i)^maisons\b", "maison", t))191                 for t in _TYPE_RE.findall(unites)}192        types.discard("")193        if len(types) == 1:194            unit_type = types.pop()195196        amenities: list[str] = []197        if count and kind:198            amenities.append(f"Immeuble de {count} {kind}")199        if unites:200            amenities.append(f"Unités en location : {unites}")201202        # vignette de la carte (ignorer le bandeau décoratif « À venir »)203        images: list[str] = []204        for img in card.select("img[src]"):205            src = img["src"]206            if src.startswith("http") and "Bandeau" not in src:207                images.append(src)208                break209210        lst = Listing(211            source=self.source_id,212            external_id=ext_id,213            url=url,214            title=f"{name} — {address}".strip(" —") or ext_id,215            address=address,216            city=city,217            unit_type=unit_type,218            price=parse_price(price_label),219            price_label=price_label,220            availability=availability,221            amenities=amenities,222            images=images,223        )224225        key = hashlib.sha1(226            f"{name}|{price_label}|{availability}|{unites}"227            .encode("utf-8")).hexdigest()228        try:229            payload = self.detail(ext_id, key,230                                  lambda u=url: self._fetch_detail(u))231            self._apply_detail(lst, payload)232        except Exception:233            pass234        listings[ext_id] = lst235236    # -- fiche immeuble (/location/<slug>/) ------------------------------------------237    def _fetch_detail(self, url: str) -> dict:238        """Services associés / à proximité et photos de la fiche."""239        if self._fetched >= self.max_details:240            raise RuntimeError("budget de fiches détail atteint")241        self._fetched += 1242        html = self.get(url).text243        soup = BeautifulSoup(html, "html.parser")244        out: dict = {}245246        text = re.sub(r"\s+", " ", soup.get_text(" | ", strip=True))247        m = re.search(r"Services \|? ?associés \|? ?: \|(.+?)(?=Services \|? ?à \|"248                      r"|Formulaire|$)", text)249        if m:250            out["services"] = [s.strip() for s in m.group(1).split("|")251                               if s.strip()][:12]252        m = re.search(r"Services \|? ?à \|? ?proximité \|? ?: \|(.+?)"253                      r"(?=Formulaire|$)", text)254        if m:255            out["nearby"] = [s.strip() for s in m.group(1).split("|")256                             if s.strip()][:12]257258        images = []259        for img in soup.select("main img[src], div[data-elementor-type] img[src]"):260            src = img["src"]261            if (src.startswith("http") and "/uploads/" in src262                    and "Bandeau" not in src and "logo" not in src.lower()263                    and src not in images):264                images.append(src)265        out["images"] = images[:15]266        return out267268    def _apply_detail(self, lst: Listing, d: dict) -> None:269        """Reporte le payload (frais ou en cache) sur l'annonce."""270        if not d:271            return272        if d.get("services"):273            lst.amenities = list(dict.fromkeys(lst.amenities + d["services"]))274        if d.get("nearby"):275            lst.description = (lst.description + "\nÀ proximité : "276                               + ", ".join(d["nearby"])).strip()277        if d.get("images") and len(d["images"]) > len(lst.images):278            lst.images = d["images"]279
Files main
Menu

Theme