SPB Git

Repository Public

lelaureat.py 9.2 KB 223 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/lelaureat.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/lelaureat.py : connecteur Résidences Le Lauréat91#   (residences-lelaureat.com) — 107 studios étudiants tout inclus rénovés au92#   2145, rue Galt Ouest, Sherbrooke (bail Régie du logement, non-fumeur,93#   occupation simple). Site WordPress WPBakery d'une seule page : la section94#   « Dimensions des studios » publie 5 TYPES d'unités (Studio Type, Centre95#   Arrière, Coin Est, Coin Ouest, Loft) avec dimensions et prix par variante96#   (étage / demi-sous-sol). Granularité = type d'unité (aucune unité97#   individuelle publiée), comme sig.py. Les inclusions communes (« Notre98#   service tout inclus englobe ») sont reprises en commodités. 1 requête.99# -----------------------------------------------------------------------------100from __future__ import annotations101102import re103104from bs4 import BeautifulSoup105106from ..schema import Listing, strip_accents107from .base import BaseConnector108109BASE = "https://www.residences-lelaureat.com"110ADDRESS = "2145 Galt Ouest, Sherbrooke, J1K 3A8"111112_AMOUNT_RE = re.compile(r"\$\s?(\d{3,4})")113_VARIANT_IMG = re.compile(r"-\d{2,4}x\d{2,4}(?=\.(?:jpg|jpeg|png|webp)$)", re.I)114115116def _slug(name: str) -> str:117    s = strip_accents(name.strip().lower())118    return re.sub(r"[^a-z0-9]+", "-", s).strip("-")119120121class LelaureatConnector(BaseConnector):122    source_id = "lelaureat"123    request_delay = 0.6124125    def fetch(self) -> list[Listing]:126        html = self.get(f"{BASE}/").text127        soup = BeautifulSoup(html, "html.parser")128129        # inclusions communes : listes de la section « tout inclus »130        common: list[str] = []131        for marker in ("Notre service tout inclus englobe",132                       "Nos appartements sont équipés"):133            el = soup.find(string=re.compile(marker))134            if not el:135                continue136            ul = el.parent.find_next("ul")137            if ul:138                for li in ul.select("li"):139                    t = re.sub(r"\s+", " ",140                               li.get_text(" ", strip=True)).strip(" ►")141                    if t and t not in common:142                        common.append(t)143144        # galerie du site (photos des studios)145        gallery: list[str] = []146        for img in soup.select("img[src*='/wp-content/uploads/']"):147            src = _VARIANT_IMG.sub("", str(img.get("src") or ""))148            if src.startswith("http") and src not in gallery \149                    and re.search(r"room-|logement|Un-logement", src):150                gallery.append(src)151152        # 5 types d'unités : titres « Studio … » / « Loft » de la section153        # dimensions, chacun précédé de sa dimension et suivi de sa liste154        # (prix par variante, particularités)155        listings: list[Listing] = []156        seen: set[str] = set()157        for h in soup.find_all(["h3", "h4", "h5"]):158            name = re.sub(r"\s+", " ", h.get_text(" ", strip=True)).strip()159            if not re.match(r"^(Studio|Loft)", name) or len(name) > 40:160                continue161            sid = _slug(name)162            if sid in seen:163                continue164            seen.add(sid)165166            dim_el = h.find_previous(string=re.compile(r"\d+\s*'"))167            dimension = re.sub(r"\s+", " ", str(dim_el)).strip() if dim_el else ""168169            # toutes les puces entre ce titre de type et le suivant : prix par170            # variante (étage / demi-sous-sol) + particularités171            bullets: list[str] = []172            for el in h.find_all_next():173                if el.name in ("h3", "h4", "h5") and re.match(174                        r"^(Studio|Loft|Façade|Galerie|Localisation)",175                        el.get_text(" ", strip=True)):176                    break177                if el.name == "li" or (el.name == "p" and178                                       "►" in el.get_text()):179                    t = re.sub(r"\s+", " ", el.get_text(" ", strip=True))180                    t = t.replace("►", " ").strip()181                    t = re.sub(r"\s+", " ", t)182                    if t and t not in bullets:183                        bullets.append(t)184185            # prix : « $855 /$825 » (étage) et « $810 » (demi-sous-sol) ->186            # le plus bas des variantes du type187            price_lines = [b for b in bullets if "$" in b]188            price_label = " / ".join(price_lines)[:80]189            amounts = [int(a) for a in _AMOUNT_RE.findall(" ".join(price_lines))]190            price = float(min(amounts)) if amounts else None191192            # disponibilité : seulement si écrite (ex. Loft « Disponibilité à193            # partir de janvier 2026 »)194            availability = ""195            for b in bullets:196                m = re.search(r"Disponibilit[eé].*$", b)197                if m:198                    availability = m.group(0).strip()199                    break200201            desc_parts = [f"Dimensions : {dimension}"] if dimension else []202            desc_parts += [b for b in bullets if b]203            amenities = [f"Dimensions : {dimension}"] if dimension else []204            amenities += common[:12]205206            listings.append(Listing(207                source=self.source_id,208                external_id=sid,209                url=f"{BASE}/",210                title=f"Résidences Le Lauréat — {name} (étudiant tout inclus)",211                address=ADDRESS,212                sector="",213                city="Sherbrooke",214                unit_type="Loft" if name.lower().startswith("loft") else "Studio",215                price=price,216                price_label=price_label,217                availability=availability,218                description=" | ".join(desc_parts)[:1000],219                amenities=amenities,220                images=gallery[:12],221            ))222        return listings223
Files main
Menu

Theme