SPB Git

Repository Public

groupe_mathieu.py 13.7 KB 341 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/groupe_mathieu.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/groupe_mathieu.py : connecteur Groupe Mathieu (groupemathieu.com)91#   Promoteur Rive-Nord : condos locatifs à Blainville (Station 54/56,92#   Le Siège Social, Place Notre Dame), Sainte-Thérèse (Ste-Thé, Quartier93#   Belmont), Terrebonne (Noüvo District) et Laval. WordPress/Elementor rendu94#   serveur : le méga-menu « PROJETS À LOUER » liste les projets par ville ;95#   chaque page projet affiche l'adresse, « Occupation … » et des blocs96#   typologie (« 3 ½ », description pi²/chambres, « À partir de N$ par mois »).97#   Granularité : une annonce par TYPOLOGIE de projet (sinon une par projet98#   quand la page ne détaille pas les typologies). Les projets « 100 % vendu/99#   loué » sont exclus.100# -----------------------------------------------------------------------------101from __future__ import annotations102103import re104105from bs4 import BeautifulSoup106107from ..schema import Listing, normalize_unit_type108from .base import BaseConnector109110BASE = "https://groupemathieu.com"111112UNIT_RE = re.compile(r"^\s*(\d)\s*½\s*$")113FROM_RE = re.compile(r"[ÀA]\s*partir\s*de\s*([\d\s  ,]+)\s*\$\s*(?:/|par)?"114                     r"\s*mois", re.I)115AREA_RE = re.compile(r"de\s*([\d\s  ]+)\s*(?:à\s*[\d\s  ]+\s*)?pi", re.I)116BED_RE = re.compile(r"(\d)\s*chambres?\b", re.I)117ADDR_RE = re.compile(118    r"\d{1,5}[^,<>\n]{3,60},?\s*(?:<br\s*/?>)?\s*"119    r"[A-Za-zÀ-ÿ\- ]{3,30},?\s*\(Qu[ée]bec\)\s*[A-Z]\d[A-Z]\s?\d[A-Z]\d")120OCC_RE = re.compile(r"Occupation\s+[^<\n]{2,40}", re.I)121SOLD_RE = re.compile(r"100\s*%\s*(?:vendu|lou[ée])", re.I)122IMG_RE = re.compile(r"https://groupemathieu\.com/wp-content/uploads/"123                    r'[^"\s\\)]+\.(?:jpe?g|png|webp)', re.I)124125126class GroupeMathieuConnector(BaseConnector):127    source_id = "groupe_mathieu"128    request_delay = 0.7129130    def fetch(self) -> list[Listing]:131        listings: list[Listing] = []132        projects: list[tuple[str, str, str]] = []   # (nom, url, ville)133134        # Découverte primaire : la page /condos-locatifs/ (rendue serveur,135        # stable) liste tous les projets locatifs via des cartes136        # « En savoir plus ». Le méga-menu Jet de l'accueil n'est servi que137        # par certaines variantes de cache Elementor → repli seulement.138        try:139            lhtml = self.get(BASE + "/condos-locatifs/").text140            lsoup = BeautifulSoup(lhtml, "html.parser")141            for a in lsoup.find_all("a", href=True):142                if "en savoir plus" not in a.get_text(" ", strip=True).lower():143                    continue144                href = a["href"].split("?")[0]145                if href.startswith("/"):146                    href = BASE + href147                if "groupemathieu.com" not in href or "promo" in href:148                    continue149                projects.append(("", href, ""))150        except Exception:151            pass152153        if not projects:154            projects = self._projects_from_menu()155156        seen: set[str] = set()157        for name, url, ville in projects:158            slug = url.rstrip("/").split("/")[-1]159            if not slug or slug in seen:160                continue161            seen.add(slug)162            try:163                listings.extend(self._fetch_project(name, url, slug, ville))164            except Exception:165                continue166        return listings167168    def _projects_from_menu(self) -> list[tuple[str, str, str]]:169        # méga-menu « PROJETS À LOUER » : colonnes ville (h5) + items projets170        try:171            html = self.get(BASE + "/").text172        except Exception:173            return []174        soup = BeautifulSoup(html, "html.parser")175        menu = None176        for title in soup.select(".jet-menu-title, .jet-menu-item"):177            if "PROJETS À LOUER" in title.get_text(" ", strip=True).upper():178                menu = title if title.name == "li" else \179                    title.find_parent("li")180                break181        if menu is None:182            return []183        sub = menu.select_one(".jet-sub-mega-menu")184        if sub is None:185            return []186187        projects: list[tuple[str, str, str]] = []188        city = ""189        for el in sub.select("h5.elementor-heading-title,"190                             " li.elementor-icon-list-item a"):191            if el.name == "h5":192                city = el.get_text(" ", strip=True).title()193                continue194            label_el = el.select_one(".elementor-icon-list-text")195            label = label_el.get_text(" ", strip=True) if label_el else ""196            if "locatif" not in label.lower():197                continue198            href = el.get("href", "")199            if href.startswith("/"):200                href = BASE + href201            strong = el.find("strong")202            name = label.replace(strong.get_text(strip=True), "").strip() \203                if strong else label204            if href:205                projects.append((name or href, href.split("?")[0], city))206        return projects207208        seen: set[str] = set()209        for name, url, ville in projects:210            slug = url.rstrip("/").split("/")[-1]211            if not slug or slug in seen:212                continue213            seen.add(slug)214            try:215                listings.extend(self._fetch_project(name, url, slug, ville))216            except Exception:217                continue218        return listings219220    def _fetch_project(self, name: str, url: str, slug: str,221                       city: str) -> list[Listing]:222        html = self.get(url).text223        if SOLD_RE.search(html):224            return []          # projet complet (ex. Vëe « 100% vendu »)225        soup = BeautifulSoup(html, "html.parser")226        text = soup.get_text("\n", strip=True)227228        address = ""229        m = ADDR_RE.search(text.replace("\n", ", "))230        if m:231            address = re.sub(r"\s+", " ", m.group(0)).replace(" ,", ",")232        if not city and address:   # découverte via /condos-locatifs/ : ville233            m = re.search(r",\s*([A-Za-zÀ-ÿ\- ']{3,30}),?\s*\(Qu", address)234            if m:235                city = m.group(1).strip().title()236        if not name:237            h1 = soup.find("h1")238            t = h1.get_text(" ", strip=True) if h1 else ""239            if not t and soup.title:240                t = soup.title.get_text(strip=True).split("|")[0].strip()241            t = re.sub(r"\s*[-–|]\s*Groupe Mathieu\s*$", "", t, flags=re.I)242            name = re.sub(r"\s+", " ", t) or slug243        availability = ""244        m = OCC_RE.search(text)245        if m:246            availability = re.sub(r"\s+", " ", m.group(0)).strip()247        rented = ""248        m = re.search(r"LOU[ÉE] À\s*\n?\s*(\d{1,3}\s*%)", text, re.I)249        if m:250            rented = m.group(1).replace(" ", "")251252        images = [u for u in dict.fromkeys(IMG_RE.findall(html))253                  if not re.search(r"logo|icon|favicon|plan|-\d{2,3}x\d{2,3}\.",254                                   u, re.I)][:20]255256        # blocs typologie, en ordre du document (dédoublés desktop/mobile)257        units: dict[str, dict] = {}258        current: str | None = None259        for el in soup.select("h2.elementor-heading-title,"260                              " .elementor-widget-text-editor p"):261            t = re.sub(r"\s+", " ", el.get_text(" ", strip=True))262            if not t:263                continue264            m = UNIT_RE.match(t)265            if m:266                ut = f"{m.group(1)}½"267                if ut in units:268                    current = None      # doublon (version mobile)269                else:270                    units[ut] = {}271                    current = ut272                continue273            if current is None:274                continue275            u = units[current]276            m = FROM_RE.search(t)277            if m and "price" not in u:278                try:279                    u["price"] = float(m.group(1).replace(" ", "")280                                       .replace(" ", "").replace(" ", "")281                                       .replace(",", ""))282                    u["price_label"] = re.sub(r"\s+", " ", m.group(0))283                except ValueError:284                    pass285                current = None          # bloc complet286                continue287            if el.name == "p" and len(t) > 40 and "desc" not in u:288                u["desc"] = t[:400]289                m = AREA_RE.search(t)290                if m:291                    try:292                        u["area"] = float(m.group(1).replace(" ", "")293                                          .replace(" ", "").replace(" ", ""))294                    except ValueError:295                        pass296                m = BED_RE.search(t)297                if m:298                    u["beds"] = float(m.group(1))299300        details: dict = {}301        if rented:302            details["taux_loue"] = rented303304        out: list[Listing] = []305        if units:306            for ut, u in units.items():307                out.append(Listing(308                    source=self.source_id,309                    external_id=f"{slug}-{ut.replace('½', '.5')}",310                    url=url,311                    title=f"{ut} — {name} ({city})",312                    address=address,313                    city=city,314                    unit_type=normalize_unit_type(ut),315                    bedrooms=u.get("beds"),316                    price=u.get("price"),317                    price_label=u.get("price_label", ""),318                    availability=availability,319                    area_sqft=u.get("area"),320                    description=u.get("desc", ""),321                    details=dict(details),322                    images=images,323                ))324        elif availability:   # page sans blocs typologie (ex. Place Notre Dame)325            desc = " ".join(p.get_text(" ", strip=True)326                            for p in soup.find_all("p")327                            if len(p.get_text(strip=True)) > 80)[:900]328            out.append(Listing(329                source=self.source_id,330                external_id=slug,331                url=url,332                title=f"{name} — condos locatifs ({city})",333                address=address,334                city=city,335                availability=availability,336                description=re.sub(r"\s+", " ", desc),337                details=dict(details),338                images=images,339            ))340        return out341
Files main
Menu

Theme