SPB Git

Repository Public

quartier_mosaique.py 8.4 KB 214 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/quartier_mosaique.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-0813# Last Modified    : 2026-08-0814#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/quartier_mosaique.py : connecteur Quartier Mosaïque (Constrobourg)91#   (quartiermosaique.com — 5 complexes : Rubis, Saphir, Opale 1-2, Perle,92#   secteur Lebourgneuf près des Galeries de la Capitale, Québec).93#   Page /unites-disponibles/ rendue serveur (WordPress, thème Browsy) : une94#   carte par plan d'unité disponible (div.cardib.unites-item) avec titre95#   (« Rubis – 3 ½ »), type (data-type), prix « À partir de X $ par mois »96#   (cardib-excerpt), description (data-desc, JSON) et galerie complète97#   (data-gallery, JSON). Aucune page détail nécessaire : tout est sur la liste.98#   Adresse du quartier publiée sur /contact/ : 2013, boulevard Lebourgneuf.99# -----------------------------------------------------------------------------100from __future__ import annotations101102import json103import re104from urllib.parse import unquote105106from bs4 import BeautifulSoup107108from ..schema import Listing, normalize_unit_type, parse_price109from .base import BaseConnector110111BASE = "https://quartiermosaique.com"112LIST_URL = f"{BASE}/unites-disponibles/"113114# Adresse du projet telle que publiée sur https://quartiermosaique.com/contact/115# (les 5 bâtiments partagent le même quadrilatère, aucune adresse par bâtiment116# n'est affichée sur le site).117PROJECT_ADDRESS = "2013, boulevard Lebourgneuf, Québec, G2K 0N8"118119120def _strip_tags(html: str) -> str:121    """'<p>Condos locatifs…</p>' -> texte brut, espaces normalisés."""122    txt = re.sub(r"<[^>]+>", " ", html or "")123    return re.sub(r"\s+", " ", txt).strip()124125126class QuartierMosaiqueConnector(BaseConnector):127    source_id = "quartier_mosaique"128    request_delay = 0.6129130    def fetch(self) -> list[Listing]:131        html = self.get(LIST_URL).text132        soup = BeautifulSoup(html, "html.parser")133134        listings: dict[str, Listing] = {}135        # les cartes sont dupliquées (grille + carrousel swiper) : dédupliquer136        for card in soup.select("div.cardib"):137            try:138                self._parse_card(card, listings)139            except Exception:140                continue141        return list(listings.values())142143    # -- carte « unité disponible » (thème Browsy) ------------------------------144    def _parse_card(self, card, listings: dict[str, Listing]) -> None:145        link = card.select_one('a[href*="/unites/"]')146        title = " ".join((card.get("data-title") or "").split())147        if not link or not title:148            return149        url = link["href"]150        m = re.search(r"/unites/([^/]+)/?", url)151        if not m:152            return153        ext_id = unquote(m.group(1))         # slug WordPress stable (« rubis-3-½ »)154        if ext_id in listings:155            return156157        # prix rendu dans la page : « À partir de 1 457 $ par mois »158        exc = card.select_one(".cardib-excerpt")159        price_label = exc.get_text(" ", strip=True) if exc else ""160161        # type d'unité structuré (data-type : « 3 ½ », « 3 ½ Bureau », « Loft »)162        raw_type = " ".join((card.get("data-type") or "").split())163        unit_type = normalize_unit_type(raw_type or title)164165        # description (attribut data-desc : chaîne JSON contenant du HTML)166        description = ""167        raw_desc = card.get("data-desc") or ""168        if raw_desc:169            try:170                description = _strip_tags(json.loads(raw_desc))171            except (ValueError, TypeError):172                description = _strip_tags(raw_desc)173174        # galerie complète (attribut data-gallery : tableau JSON de médias)175        images: list[str] = []176        raw_gallery = card.get("data-gallery") or ""177        if raw_gallery:178            try:179                for media in json.loads(raw_gallery):180                    u = (media or {}).get("url") or ""181                    if u.startswith("http") and u not in images:182                        images.append(u)183            except (ValueError, TypeError):184                pass185        if not images:186            img = card.select_one("img[src]")187            if img and img["src"].startswith("http"):188                images = [img["src"]]189190        # bâtiment : préfixe du titre (« Rubis – 3 ½ » -> « Rubis »)191        building = title.split("–")[0].strip()192193        details: dict = {}194        if building:195            details["building"] = building196        if re.search(r"\bbureau\b", raw_type, re.I):197            details["office_nook"] = True    # variante avec coin bureau198199        listings[ext_id] = Listing(200            source=self.source_id,201            external_id=ext_id,202            url=url,203            title=title,204            address=PROJECT_ADDRESS,205            sector="Lebourgneuf",206            city="Québec",207            unit_type=unit_type,208            price=parse_price(price_label),209            price_label=price_label,210            description=description,211            details=details,212            images=images[:20],213        )214
Files main
Menu

Theme