SPB Git

Repository Public

laureat_richard.py 12.5 KB 299 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/laureat_richard.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/laureat_richard.py : connecteur Logements Lauréat Richard91#   (laureatrichard.com — Sherbrooke, quartier Nord, 700+ appartements gérés).92#   WordPress + thème Avada (fusion) + plugin WP-Property : page93#   /nos-immeubles-a-logements/ -> 8 pages immeuble (Le Plateau Richard,94#   Complexe Lunik, Carré McGregor…), chacune listant ses modèles de logements95#   offerts (`.property_div` : titre + lien + plan). Fiches /proprietes/<slug>96#   via self.detail() (cache BD) : bloc structuré `#wpp_property_stats`97#   (Grandeur, Inclus dans le logement, Adresse), description et plans.98#   LE SITE NE PUBLIE NI PRIX NI DATE DE DISPONIBILITÉ : ces champs restent99#   vides (jamais de valeur inventée) — contact par téléphone/visite.100# -----------------------------------------------------------------------------101from __future__ import annotations102103import hashlib104import re105106from bs4 import BeautifulSoup107108from ..schema import Listing, normalize_unit_type, strip_accents109from .base import BaseConnector110111BASE = "https://laureatrichard.com"112LIST_URL = f"{BASE}/nos-immeubles-a-logements/"113114_PROP_RE = re.compile(r"/proprietes/([\w\-%]+)/?$")115116117class LaureatRichardConnector(BaseConnector):118    source_id = "laureat_richard"119    request_delay = 0.6120    max_details = 40          # garde-fou : vraies requêtes de fiches propriété121122    def fetch(self) -> list[Listing]:123        # 1) Page index -> pages immeuble (URLs normalisées, dédupliquées)124        html = self.get(LIST_URL).text125        soup = BeautifulSoup(html, "html.parser")126        building_urls: list[str] = []127        for a in soup.select('a[href*="/nos-immeubles-a-logements/"]'):128            url = (a.get("href") or "").split("?")[0].rstrip("/") + "/"129            if url != LIST_URL and url.startswith(LIST_URL) and url not in building_urls:130                building_urls.append(url)131132        # 2) Pages immeuble : nom, description, particularités + modèles offerts133        listings: dict[str, Listing] = {}134        for burl in building_urls:135            try:136                bhtml = self.get(burl).text137            except Exception:138                continue139            bsoup = BeautifulSoup(bhtml, "html.parser")140            h1 = bsoup.select_one("h1.entry-title, h1")141            building = h1.get_text(" ", strip=True) if h1 else ""142            b_desc = self._text_after_heading(bsoup, r"Description des immeubles")143            b_amen = self._particularites(bsoup)144145            for item in bsoup.select("div.property_div"):146                link = item.select_one("li.property_title a[href], a[href]")147                if not link:148                    continue149                url = link["href"]150                m = _PROP_RE.search(url)151                if not m:152                    continue153                slug = m.group(1)154                if slug in listings:155                    continue156                title = link.get_text(" ", strip=True)157                thumb = item.select_one("img[src]")158                images = ([thumb["src"]] if thumb159                          and thumb.get("src", "").startswith("http") else [])160                listings[slug] = Listing(161                    source=self.source_id,162                    external_id=slug,163                    url=url,164                    title=title or slug.replace("-", " "),165                    city="Sherbrooke",166                    unit_type=normalize_unit_type(title),167                    description=b_desc[:600],168                    amenities=list(b_amen),169                    details={"building": building} if building else {},170                    images=images,171                )172173        # 3) Fiches propriété (cache BD) : Grandeur / Inclus / Adresse,174        #    description du logement, plans175        self._fetched = 0176        for lst in listings.values():177            key = hashlib.sha1(f"{lst.title}|{lst.url}".encode("utf-8")).hexdigest()178179            def fetch_fn(u=lst.url):180                if self._fetched >= self.max_details:181                    raise RuntimeError("budget de fiches détail atteint")182                self._fetched += 1183                return self._fetch_detail(u)184185            try:186                payload = self.detail(lst.external_id, key, fetch_fn)187            except Exception:188                continue189            self._apply_detail(lst, payload)190191        return list(listings.values())192193    # -- blocs Avada (fusion) -----------------------------------------------------194    @staticmethod195    def _text_after_heading(soup, pattern: str) -> str:196        """Texte du bloc fusion-text qui suit un titre donné (page immeuble)."""197        h = soup.find(["h2", "h3"], string=re.compile(pattern))198        if not h:199            return ""200        cont = h.find_parent(class_=re.compile("fusion-title")) or h201        node = cont202        for _ in range(4):203            node = node.find_next_sibling()204            if node is None:205                break206            if "fusion-text" in (node.get("class") or []):207                return " ".join(node.get_text(" ", strip=True).split())208        return ""209210    @staticmethod211    def _particularites(soup) -> list[str]:212        """Items de la liste « Particularités » de l'immeuble."""213        h = soup.find("h3", string=re.compile(r"^\s*Particularités\s*$"))214        if not h:215            return []216        cont = h.find_parent(class_=re.compile("fusion-title")) or h217        node = cont218        for _ in range(4):219            node = node.find_next_sibling()220            if node is None:221                break222            if "fusion-text" in (node.get("class") or []):223                items = [li.get_text(" ", strip=True) for li in node.select("li")]224                items = [i for i in items if i]225                if items:226                    return items[:15]227                txt = " ".join(node.get_text(" ", strip=True).split())228                return [txt] if txt else []229        return []230231    # -- fiche propriété (WP-Property) ---------------------------------------------232    def _fetch_detail(self, url: str) -> dict:233        html = self.get(url).text234        soup = BeautifulSoup(html, "html.parser")235        out: dict = {}236237        # stats structurées : Grandeur / Inclus dans le logement / Adresse238        for li in soup.select("#wpp_property_stats li"):239            lab_el = li.select_one("span.attribute")240            val_el = li.select_one("span.value")241            if not (lab_el and val_el):242                continue243            lab = strip_accents(lab_el.get_text(" ", strip=True).lower())244            val = " ".join(val_el.get_text(" ", strip=True).split()).rstrip(",")245            if lab.startswith("grandeur"):246                out["grandeur"] = val247            elif lab.startswith("inclus"):248                out["inclus"] = [x.strip() for x in val.split(",") if x.strip()]249            elif lab.startswith("adresse"):250                out["address"] = val251252        # description du logement (paragraphes après le titre wpp_title)253        title_el = soup.find("div", class_="wpp_title",254                             string=re.compile("Description du logement"))255        if title_el:256            paras = []257            node = title_el258            for _ in range(8):259                node = node.find_next_sibling()260                if node is None or node.name not in ("p",):261                    break262                t = " ".join(node.get_text(" ", strip=True).split())263                if t:264                    paras.append(t)265            if paras:266                out["description"] = " ".join(paras)[:1200]267268        # plans des modèles (grande taille via les liens de la galerie)269        images: list[str] = []270        for a in soup.select('a[href*="/wp-content/uploads/"]'):271            href = a["href"]272            if re.search(r"\.(jpe?g|png|webp)$", href, re.I) and href not in images:273                images.append(href)274        for img in soup.select('img[src*="/wp-content/uploads/"]'):275            src = img["src"]276            if (re.search(r"\.(jpe?g|png|webp)$", src, re.I)277                    and not re.search(r"logo", src, re.I) and src not in images):278                images.append(src)279        out["images"] = images[:20]280        return out281282    def _apply_detail(self, lst: Listing, d: dict) -> None:283        if not d:284            return285        if d.get("address"):286            # « 2975, rue Richard, Sherbrooke, QC J1L 2X5, Canada »287            lst.address = re.sub(r",?\s*Canada$", "", d["address"])288        if d.get("grandeur"):289            lst.unit_type = normalize_unit_type(d["grandeur"]) or lst.unit_type290        if d.get("inclus"):291            lst.amenities = list(dict.fromkeys(d["inclus"] + lst.amenities))292        if d.get("description"):293            # description propre au logement d'abord, contexte immeuble ensuite294            building_desc = lst.description295            lst.description = (d["description"] +296                               (f" | {building_desc}" if building_desc else ""))[:1200]297        if d.get("images"):298            lst.images = list(dict.fromkeys(d["images"] + lst.images))[:20]299
Files main
Menu

Theme