SPB Git

Repository Public

beaulieu_groupe.py 13.2 KB 310 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/beaulieu_groupe.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-0913# Last Modified    : 2026-10-1514#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/beaulieu_groupe.py : connecteur Beaulieu Groupe Immobilier / BGI91#   (beaulieugroupeimmobilier.com — Rimouski, Bas-Saint-Laurent ; distinct des92#   Immeubles Beaulieu et Collin `immeubles_bc` et de Beaulieu Gestion à93#   Rivière-du-Loup). WordPress + Elementor avec un shortcode maison :94#     - archive /batiment/?category=residentiel : cartes `div.card-batiment`95#       par immeuble avec statut « COMPLET » ou « Locaux disponibles : N » ;96#     - fiche /batiment/<slug>/ : description de l'immeuble + cartes d'unités97#       `div.card-local` (« 418 Alcide-C.-Horth, app #206 | 4 1/2 ») dont le98#       `p.card-text` vaut « Indisponible » (image générique Complet.png) ou,99#       pour les unités libres, « Superficie : N pi² » avec photo réelle.100#   Le connecteur ne visite que les fiches des immeubles NON marqués COMPLET101#   (politesse) et n'émet que les unités non « Indisponible ». Aucun prix102#   publié -> price=None, rien d'inventé. Tout le parc affiché est à Rimouski.103#   external_id stable : slug de la fiche + numéro d'appartement104#   (418-rue-alcide-c-horth--app-206).105#   robots.txt Yoast ouvert (Disallow vide), sitemap public.106# -----------------------------------------------------------------------------107from __future__ import annotations108109import re110111from bs4 import BeautifulSoup112113from ..schema import Listing, normalize_unit_type114from .base import BaseConnector115116BASE = "https://beaulieugroupeimmobilier.com"117LIST_URL = f"{BASE}/batiment/?category=residentiel"118119# Deux formats d'en-tête observés :120#   « 418 Alcide-C.-Horth, app #206 | 4 1/2 »   (gabarit 2026)121#   « 304 rue Laval-Nord, appartement 2 »        (gabarit 2026-10)122_UNIT_RE = re.compile(123    r"^(.*?),?\s*app(?:artement|\.)?\s*#?\s*(\w+)\s*(?:\|\s*(.+))?$", re.I)124_BG_IMG_RE = re.compile(r"url\(\s*['\"]?([^'\")]+)['\"]?\s*\)")125_AREA_RE = re.compile(r"superficie\s*:?\s*([\d\s,]+)\s*pi", re.I)126# « 1295$ par mois » / « 1 295$ par mois » — groupes de milliers stricts pour ne127# pas avaler le n° d'appartement qui précède (« appartement 2 1295$ »)128_PRICE_RE = re.compile(129    r"(\d{1,3}(?:[\s\u00a0\u202f]\d{3})*|\d+)\s*\$\s*par\s*mois", re.I)130_TYPE_RE = re.compile(r"(\d+\s*(?:½|1/2))")131_AVAIL_RE = re.compile(r"disponibles?\s*:\s*(\d+)", re.I)132133134class BeaulieuGroupeConnector(BaseConnector):135    source_id = "beaulieu_groupe"136    request_delay = 0.6137    max_detail = 12                     # plafond de fiches visitées par sync138139    def fetch(self) -> list[Listing]:140        soup = BeautifulSoup(self.get(LIST_URL).text, "html.parser")141142        cards = soup.select("div.card-batiment")143        if not cards:144            raise RuntimeError(145                "beaulieu_groupe : aucune div.card-batiment sur l'archive — "146                "gabarit remanié, parseur à revoir")147148        listings: dict[str, Listing] = {}149        announced = 0                   # unités annoncées « Locaux disponibles : N »150        visited = 0151        for card in cards:152            link = card.select_one('a[href*="/batiment/"]')153            if link is None:154                continue155            url = link["href"].strip()156            status = ""157            for p in card.select("p"):158                t = p.get_text(" ", strip=True)159                if t and "VOIR LA FICHE" not in t.upper():160                    status = t161                    break162            m_avail = _AVAIL_RE.search(status)163            if m_avail:164                announced += int(m_avail.group(1))165            # les immeubles COMPLET n'ont aucune unité libre : fiche non visitée166            if "COMPLET" in status.upper() or visited >= self.max_detail:167                continue168            visited += 1169            try:170                self._parse_building(url, listings)171            except Exception:172                continue173        # garde-fou anti zéro silencieux : l'archive annonce des unités libres174        # mais rien n'a été parsé -> gabarit des fiches changé, erreur FRANCHE175        if announced > 0 and not listings:176            raise RuntimeError(177                f"beaulieu_groupe : archive annonce {announced} unité(s) "178                "disponible(s) mais 0 parsée — gabarit des fiches changé ?")179        return list(listings.values())180181    # -- fiche d'immeuble (/batiment/<slug>/) -------------------------------------182    def _parse_building(self, url: str, listings: dict[str, Listing]) -> None:183        m = re.search(r"/batiment/([^/?#]+)", url)184        if not m:185            return186        slug = m.group(1)187        soup = BeautifulSoup(self.get(url).text, "html.parser")188189        # description de l'immeuble (paragraphes Elementor avant la liste)190        paras = [p.get_text(" ", strip=True)191                 for p in soup.select(".elementor-widget-text-editor p")]192        description = "\n".join(t for t in paras if len(t) >= 40)[:1200]193194        for card in soup.select("div.card-local"):195            h5 = card.select_one("h5")196            info = card.select_one("p.card-text")197            if h5 is None:198                continue199            head = re.sub(r"\s+", " ", h5.get_text(" ", strip=True))200            info_txt = re.sub(201                r"\s+", " ", info.get_text(" ", strip=True)) if info else ""202            if re.search(r"(?i)indisponible", info_txt):203                continue                       # unité louée204205            m_unit = _UNIT_RE.match(head)206            if not m_unit:207                continue                       # carte sans n° d'app (bandeau)208            addr, app_no, type_txt = (m_unit.group(1).strip(),209                                      m_unit.group(2),210                                      (m_unit.group(3) or "").strip())211212            ext_id = f"{slug}--app-{app_no.lower()}"213            if ext_id in listings:214                continue215216            area = None217            m_area = _AREA_RE.search(info_txt)218            if m_area:219                try:220                    area = float(m_area.group(1).replace(" ", "")221                                 .replace(" ", "").replace(",", "."))222                except ValueError:223                    area = None224225            images: list[str] = []226            img = card.select_one(".card-img-top")227            if img is not None:228                m_bg = _BG_IMG_RE.search(img.get("style", ""))229                if m_bg and m_bg.group(1).startswith("http") \230                        and "Complet" not in m_bg.group(1):231                    images.append(m_bg.group(1))232233            # gabarit 2026-10 : la carte pointe vers une page d'unité234            # /local/<slug>/ qui publie désormais le loyer, le type et les photos235            price = None236            unit_url = url237            unit_link = card.select_one('a[href*="/local/"]')238            if unit_link is not None and unit_link.get("href", "").startswith("http"):239                unit_url = unit_link["href"].strip()240                detail = self._parse_unit_page(unit_url)241                price = detail.get("price")242                type_txt = type_txt or detail.get("unit_type") or ""243                area = area if area is not None else detail.get("area")244                if detail.get("description"):245                    description = detail["description"]246                for u in detail.get("images", []):247                    if u not in images:248                        images.append(u)249250            listings[ext_id] = Listing(251                source=self.source_id,252                external_id=ext_id,253                url=unit_url,254                title=head,255                address=f"{addr}, Rimouski" if addr else "",256                city="Rimouski",             # tout le parc affiché est à Rimouski257                unit_type=normalize_unit_type(type_txt),258                price=price,                  # publié depuis le gabarit 2026-10 seulement259                price_label="",260                availability="",              # libre = non « Indisponible » ; pas de date fiable261                area_sqft=area,262                description=description,263                images=images,264            )265266    # -- page d'unité (/local/<slug>/, gabarit 2026-10) ----------------------------267    def _parse_unit_page(self, url: str) -> dict:268        soup = BeautifulSoup(self.get(url).text, "html.parser")269        main = soup.select_one('[data-elementor-type="single-page"]') or soup270        text = main.get_text(" ", strip=True)271272        price = None273        m = _PRICE_RE.search(text)274        if m:275            try:276                price = float(re.sub(r"\D", "", m.group(1)))277            except ValueError:278                price = None279280        unit_type = ""281        title = soup.title.get_text(" ", strip=True) if soup.title else ""282        m = _TYPE_RE.search(title) or _TYPE_RE.search(text)283        if m:284            unit_type = m.group(1)285286        area = None287        m = _AREA_RE.search(text)288        if m:289            try:290                area = float(m.group(1).replace(" ", "")291                             .replace(" ", "").replace(",", "."))292            except ValueError:293                area = None294295        paras = [re.sub(r"\s+", " ", w.get_text(" ", strip=True))296                 for w in main.select(".elementor-widget-text-editor")]297        description = "\n".join(298            t for t in paras if len(t) >= 60 and "par mois" not in t.lower())[:1200]299300        images = []301        for img in main.select("img"):302            src = (img.get("src") or "").strip()303            if (src.startswith("http") and "/uploads/" in src304                    and "logo" not in src.lower() and "Complet" not in src305                    and src not in images):306                images.append(src)307308        return {"price": price, "unit_type": unit_type, "area": area,309                "description": description, "images": images}310
Files main
Menu

Theme