SPB Git

Repository Public

immeubles_pm.py 11.7 KB 285 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/immeubles_pm.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/immeubles_pm.py : connecteur Les Immeubles PM (lesimmeublespm.com)91#   Parc familial de Sherbrooke (Fleurimont, Sherbrooke Est) — 6 immeubles.92#   Plateforme « plogg solutions » (même famille que appartementsgranby.com /93#   godbout, resté non connectable faute d'unités libres) : la page d'accueil94#   rend côté serveur le bloc #listing-appart — une carte .box par immeuble95#   AVEC UNITÉS LIBRES seulement, contenant un tableau Grandeur / Loyer96#   (« à partir de 1475$ ») / Disponible + lien « Consulter la fiche ».97#   La recherche (form-manager.php) est fermée aux robots, mais les fiches98#   /appartement/<slug>/ restent servies : self.detail (cache BD) y lit le99#   tableau complet (rue, ville, quartier, superficie, étage, salles de bain,100#   état), la description (div.extrait) et la galerie. external_id = slug de101#   la fiche (stable, un par unité-type d'immeuble).102# -----------------------------------------------------------------------------103from __future__ import annotations104105import hashlib106import re107108from bs4 import BeautifulSoup109110from ..schema import Listing, normalize_unit_type, parse_price, strip_accents111from .base import BaseConnector112113BASE = "https://www.lesimmeublespm.com"114115_SIZE_SUFFIX = re.compile(r"-\d{2,4}x\d{2,4}(?=\.(?:jpg|jpeg|png|webp)$)", re.I)116117118def _clean_unit_type(raw: str) -> str:119    ut = normalize_unit_type(raw or "")120    if re.fullmatch(r"\d½\+?|6½\+|Studio|Loft|Chambre|Maison", ut or ""):121        return ut122    return ""123124125class ImmeublesPMConnector(BaseConnector):126    source_id = "immeubles_pm"127    request_delay = 0.7128    max_details = 25       # garde-fou fiches détail (vraies requêtes)129130    def fetch(self) -> list[Listing]:131        html = self.get(BASE + "/").text132        soup = BeautifulSoup(html, "html.parser")133134        listings: dict[str, Listing] = {}135        listing_root = soup.select_one("#listing-appart") or soup136        for box in listing_root.select("div.box"):137            try:138                self._parse_box(box, listings)139            except Exception:140                continue141142        # fiches détail (cache BD) : adresse, superficie, étage, description…143        self._fetched = 0144        for lst in listings.values():145            card_key = hashlib.sha1(146                f"{lst.title}|{lst.price_label}|{lst.availability}"147                .encode("utf-8")).hexdigest()148            try:149                payload = self.detail(lst.external_id, card_key,150                                      lambda u=lst.url: self._fetch_detail(u))151            except Exception:152                continue153            self._apply_detail(lst, payload)154        return list(listings.values())155156    # -- carte immeuble de l'accueil (tableau des unités libres) -----------------157    def _parse_box(self, box, listings: dict[str, Listing]) -> None:158        title_el = box.select_one(".box-content-title")159        building = title_el.get_text(" ", strip=True) if title_el else ""160        quartier = ""161        q_el = box.select_one(".box-content-quartier")162        if q_el:163            quartier = re.sub(r"^\s*Quartier\s*:?\s*", "",164                              q_el.get_text(" ", strip=True), flags=re.I).strip()165166        photo = ""167        ph_el = box.select_one(".photo-wrapper[style]")168        if ph_el:169            m = re.search(r"url\('([^']+)'\)", ph_el.get("style") or "")170            if m:171                photo = _SIZE_SUFFIX.sub("", m.group(1))172173        # tableau bureau (les blocs mobiles dupliquent les mêmes unités)174        for row in box.select(".hide-on-mobile table tbody tr"):175            link = row.select_one('a[href*="/appartement/"]')176            if not link:177                continue178            url = link["href"]179            m = re.search(r"/appartement/([^/?#]+)", url)180            if not m:181                continue182            ext_id = m.group(1)183            if ext_id in listings:184                continue185            cells = row.find_all("td")186            grandeur = cells[0].get_text(" ", strip=True) if cells else ""187            price_label = re.sub(r"\s+", " ", cells[1].get_text(188                " ", strip=True)).strip() if len(cells) > 1 else ""189            availability = re.sub(r"\s+", " ", cells[2].get_text(190                " ", strip=True)).strip() if len(cells) > 2 else ""191            if re.search(r"complet|lou[ée]\b", availability, re.I):192                continue193194            title = f"{grandeur} — {building}".strip(" —")195            listings[ext_id] = Listing(196                source=self.source_id,197                external_id=ext_id,198                url=url,199                title=re.sub(r"\s+", " ", title).strip(),200                address=building,        # nom d'immeuble = adresse civique201                sector=quartier,202                city="Sherbrooke",       # précisé par la fiche (champ Ville)203                unit_type=_clean_unit_type(grandeur),204                price=parse_price(price_label),205                price_label=price_label,206                availability=availability,207                images=[photo] if photo else [],208            )209210    # -- fiche /appartement/<slug>/ -----------------------------------------------211    def _fetch_detail(self, url: str) -> dict:212        if self._fetched >= self.max_details:213            raise RuntimeError("budget de fiches détail atteint")214        self._fetched += 1215        html = self.get(url).text216        soup = BeautifulSoup(html, "html.parser")217        out: dict = {}218219        # tableau infos-appart : paires <td.sub-title><b>Champ</b></td><td>valeur220        pairs: dict[str, str] = {}221        for row in soup.select(".infos-appart table tr"):222            cells = row.find_all("td")223            if len(cells) < 2:224                continue225            lab = strip_accents(cells[0].get_text(" ", strip=True).lower())226            val = re.sub(r"\s+", " ", cells[1].get_text(" ", strip=True)).strip()227            val = re.sub(r"\bpi\s*2\b", "pi²", val)   # « 1510 pi<sup>2</sup> »228            if lab and val:229                pairs[lab] = val230        if pairs.get("rue"):231            out["address"] = pairs["rue"]232        if pairs.get("ville"):233            out["city"] = pairs["ville"]234        if pairs.get("quartier"):235            out["sector"] = pairs["quartier"]236        if pairs.get("grandeur"):237            out["grandeur"] = pairs["grandeur"]238        if pairs.get("etat"):239            out["etat"] = pairs["etat"]240        amenities = []241        for lab, label in [("superficie", "Superficie"),242                           ("etage", "Étage"),243                           ("nombre de salle de bain", "Salle(s) de bain")]:244            if pairs.get(lab):245                amenities.append(f"{label} : {pairs[lab]}")246        out["amenities"] = amenities247248        # description : bloc div.extrait (texte + liste d'inclusions)249        ext = soup.select_one("div.extrait")250        if ext:251            txt = ext.get_text("\n", strip=True)252            out["description"] = re.sub(r"[ \t]+", " ", txt).strip()[:1500]253254        # galerie : photos jpg des téléversements (icônes png exclues)255        images: list[str] = []256        for u in re.findall(257                r"https://www\.lesimmeublespm\.com/wp-content/uploads/"258                r"[^\"'()\s]+\.(?:jpg|jpeg|webp)", html, re.I):259            u = _SIZE_SUFFIX.sub("", u)260            if u not in images:261                images.append(u)262        out["images"] = images[:30]263        return out264265    def _apply_detail(self, lst: Listing, d: dict) -> None:266        if not d:267            return268        if d.get("address"):269            lst.address = d["address"]270        if d.get("city"):271            lst.city = d["city"]272        if d.get("sector") and not lst.sector:273            lst.sector = d["sector"]274        if not lst.unit_type and d.get("grandeur"):275            lst.unit_type = _clean_unit_type(d["grandeur"])276        if not lst.availability and d.get("etat"):277            lst.availability = d["etat"]278        if d.get("amenities"):279            lst.amenities = list(dict.fromkeys(lst.amenities + d["amenities"]))280        if d.get("description"):281            lst.description = d["description"]282        if d.get("images"):283            merged = list(dict.fromkeys(d["images"] + lst.images))284            lst.images = merged[:30]285
Files main
Menu

Theme