SPB Git

Repository Public

saint_michel.py 10.0 KB 263 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/saint_michel.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-2513# Last Modified    : 2026-08-2514#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/saint_michel.py : connecteur Le Saint-Michel (lesaintmichel.ca)91#   3250, boul. Henri-Bourassa Est, Montréal-Nord — studios à 5½ (unités A/B/C).92#   Contrairement au repérage initial (« shell JS »), la page /appartements/93#   est rendue SERVEUR : une carte <a class="unit js-unit"> par unité avec94#   data-status="1" quand elle est disponible (étage, superficie « +/- 82995#   p.ca », « à partir de *1749 », type dans l'alt du plan). La fiche96#   /units/unite-<x>/ (cache BD) ajoute description, date de disponibilité97#   et plan haute résolution. Repli Scrapfly si le GET direct est bloqué.98# -----------------------------------------------------------------------------99from __future__ import annotations100101import hashlib102import re103104from bs4 import BeautifulSoup105106from ..schema import Listing107from .base import BaseConnector108109BASE = "https://lesaintmichel.ca"110LIST_URL = f"{BASE}/appartements/"111ADDRESS = "3250, boul. Henri-Bourassa Est, Montréal-Nord, Montréal, QC H1H 1H4"112113_TYPE_RE = re.compile(r"Plan\s+(\d\s*1/2|\d\s*½|Studio|Loft)", re.I)114_PRICE_RE = re.compile(r"\*?\s*([\d]{3,4})\s*\$?")115_SQFT_RE = re.compile(r"([\d\s]{3,6})\s*p\.?\s*ca", re.I)116_FLOOR_RE = re.compile(r"^([\d,\s]+)\s*Étage", re.I)117_IMG_RE = re.compile(118    r'https://lesaintmichel\.ca/wp-content/uploads/[^"\'\s\\)]+?'119    r'\.(?:jpg|jpeg|png|webp)', re.I)120_SKIP_IMG = re.compile(r"logo|icon|favicon|-\d{2,4}x\d{2,4}\.", re.I)121122123class SaintMichelConnector(BaseConnector):124    source_id = "saint_michel"125    request_delay = 0.6126    max_images = 20127128    def _list_html(self) -> str:129        """HTML de la liste : direct d'abord, Scrapfly (ASP) en repli."""130        try:131            html = self.get(LIST_URL).text132            if "js-unit" in html:133                return html134        except Exception:135            pass136        return self.get_scrapfly(LIST_URL, render_js=False)137138    def fetch(self) -> list[Listing]:139        soup = BeautifulSoup(self._list_html(), "html.parser")140141        listings: list[Listing] = []142        for card in soup.select("a.unit.js-unit"):143            try:144                if card.get("data-status") != "1":145                    continue         # unité indisponible146                lst = self._card_listing(card)147                if lst is not None:148                    listings.append(lst)149            except Exception:150                continue151        return listings152153    def _card_listing(self, card) -> Listing | None:154        url = card.get("href") or ""155        slug = url.rstrip("/").split("/")[-1]      # ex. « unite-b1 »156        if not slug:157            return None158159        spans = [s.get_text(" ", strip=True) for s in card.select("span")]160        text = " | ".join(spans)161162        # nom de l'unité (« Unité B1 ») et étage(s) (« 5 Étage »)163        name = next((s for s in spans if s.lower().startswith("unité")), slug)164        floor = ""165        for s in spans:166            fm = _FLOOR_RE.match(s)167            if fm:168                floor = fm.group(1).strip(" ,")169                break170171        # type dans l'alt du plan (« Plan 4 1/2 - Unité B1 - … »)172        unit_type = ""173        img = card.select_one("img")174        alt = (img.get("alt") or "") if img else ""175        tm = _TYPE_RE.search(alt)176        if tm:177            unit_type = (tm.group(1).replace(" ", "").replace("1/2", "½")178                         .capitalize() if "tudio" in tm.group(1).lower()179                         or "oft" in tm.group(1).lower()180                         else tm.group(1).replace(" ", "").replace("1/2", "½"))181182        # prix « à partir de | *1749 »183        price = None184        if "à partir de" in text.lower():185            for s in spans:186                pm = _PRICE_RE.fullmatch(s.strip())187                if pm:188                    price = float(pm.group(1))189                    break190        if price is not None and not (100 <= price <= 20000):191            price = None192193        # superficie « +/- 829 p.ca + loggia 107 p.ca » (surface principale)194        sqft = None195        sq_label = next((s for s in spans if "p.ca" in s), "")196        sm = _SQFT_RE.search(sq_label)197        if sm:198            try:199                sqft = float(re.sub(r"\s", "", sm.group(1)))200            except ValueError:201                sqft = None202203        # fiche de l'unité (cache BD) : description, dispo, plan hi-res204        key = hashlib.sha1(f"{text}|{price}".encode("utf-8")).hexdigest()205        d = self.detail(slug, key, lambda: self._fetch_unit(url))206207        details: dict = {}208        if floor:209            details["floor"] = floor210        if sq_label:211            details["Superficie"] = sq_label212213        return Listing(214            source=self.source_id,215            external_id=slug,216            url=url,217            title=f"Le Saint-Michel — {name}"218                  + (f" ({unit_type})" if unit_type else ""),219            address=ADDRESS,220            sector="Montréal-Nord",221            city="Montréal",222            unit_type=unit_type,223            price=price,224            price_label=f"À partir de {int(price)} $/mois" if price else "",225            availability=d.get("availability") or "Disponible",226            area_sqft=sqft,227            description=d.get("desc", ""),228            details=details,229            images=d.get("images") or [],230        )231232    def _fetch_unit(self, url: str) -> dict:233        """Fiche /units/unite-<x>/ : description, disponibilité, images."""234        out: dict = {"desc": "", "availability": "", "images": []}235        try:236            html = self.get(url).text237        except Exception:238            html = self.get_scrapfly(url, render_js=False)239        if not html:240            return out241        soup = BeautifulSoup(html, "html.parser")242243        # description : premiers paragraphes substantiels de la fiche244        paras = [p.get_text(" ", strip=True) for p in soup.select("p")]245        paras = [p for p in paras if len(p) > 80]246        if paras:247            out["desc"] = " ".join(paras[:2])[:600]248249        # « Date de disponibilité | Occupation immédiate »250        txt = soup.get_text(" | ", strip=True)251        am = re.search(r"Date de disponibilité\s*\|\s*([^|]{3,60})", txt)252        if am:253            out["availability"] = am.group(1).strip()254255        images: list[str] = []256        for u in _IMG_RE.findall(html):257            if _SKIP_IMG.search(u):258                continue259            if u not in images:260                images.append(u)261        out["images"] = images[: self.max_images]262        return out263
Files main
Menu

Theme