SPB Git

Repository Public

ocartier.py 8.5 KB 218 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/ocartier.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/ocartier.py : connecteur OCartier 2 (ocartier.ca — TDR91#   Développements). Tour locative de 200 appartements au 30, rue St-Hubert92#   à Laval (métro Cartier, secteur Pont-Viau), loyer tout inclus93#   (électricité, chauffage, climatisation, eau, internet).94#   WordPress/Elementor rendu serveur : la page /plans/ affiche une95#   fourchette de prix par TYPOLOGIE (« Studios / 3 1/2 / 4 1/2 / 5 1/2 »,96#   « À partir de X $ jusqu'à Y $ »). Granularité TYPOLOGIE.97# -----------------------------------------------------------------------------98from __future__ import annotations99100import re101102from bs4 import BeautifulSoup103104from ..schema import Listing, normalize_unit_type105from .base import BaseConnector106107BASE = "https://ocartier.ca"108PAGE_URL = f"{BASE}/plans/"109110ADDRESS = "30, rue St-Hubert"111CITY = "Laval"112SECTOR = "Pont-Viau"113114BUILDING_AMENITIES = [115    "Électricité incluse", "Chauffage inclus", "Climatisation incluse",116    "Eau incluse", "Internet inclus",117]118119TYPE_RE = re.compile(r"^(?:Studios?|\d\s*(?:1/2|½))$", re.I)120RANGE_RE = re.compile(121    r"À partir de\s*([\d\s  ,]+?)\s*\$.*?jusqu[’']à\s*([\d\s  ,]+?)\s*\$",122    re.I | re.S)123BED_RE = re.compile(r"(\d)\s*chambres?", re.I)124IMG_RE = re.compile(125    r"https://ocartier\.ca/wp-content/uploads/[^\"'\s\\)]+?"126    r"\.(?:jpg|jpeg|png|webp)", re.I)127128129def _num(txt: str) -> float | None:130    digits = re.sub(r"[^\d]", "", txt or "")131    return float(digits) if digits else None132133134class OCartierConnector(BaseConnector):135    source_id = "ocartier"136    request_delay = 0.6137138    def fetch(self) -> list[Listing]:139        listings: list[Listing] = []140        try:141            html = self.get(PAGE_URL).text142        except Exception:143            return listings144        soup = BeautifulSoup(html, "html.parser")145146        # photos : la page /plans/ est pauvre en visuels, on complète avec la147        # galerie de la page /appartements/ (rendue serveur elle aussi)148        pool = IMG_RE.findall(html)149        try:150            pool += IMG_RE.findall(self.get(f"{BASE}/appartements/").text)151        except Exception:152            pass153        images = [u for u in dict.fromkeys(pool)154                  if not re.search(r"logo|favicon|icon|metro|-\d+x\d+\.", u,155                                   re.I)][:20]156157        seen: set[str] = set()158        # blocs typologie : <h4>Studios</h4> … « À partir de 1 630 $ jusqu'à … »159        # — le prix est dans un widget texte qui SUIT le heading dans l'ordre160        # du document (structure de conteneurs Elementor variable) : on161        # concatène le texte jusqu'au prochain heading de typologie.162        headings = [x for x in soup.select(".elementor-heading-title")163                    if TYPE_RE.match(x.get_text(" ", strip=True))]164        for heading in headings:165            label = heading.get_text(" ", strip=True)166            texts: list[str] = []167            for node in heading.find_all_next(string=True):168                t = str(node).strip()169                if not t:170                    continue171                if TYPE_RE.match(t) and t != label:172                    break173                texts.append(t)174                if len(texts) > 40:175                    break176            blob = " ".join(texts)177            m = RANGE_RE.search(blob)178            if not m:179                continue180            lo, hi = _num(m.group(1)), _num(m.group(2))181            if not lo:182                continue183            unit_type = ("Studio" if label.lower().startswith("studio")184                         else normalize_unit_type(label))185            ext_id = ("ocartier2-"186                      + unit_type.replace("½", ".5").replace(" ", "").lower())187            if ext_id in seen:      # les blocs sont répétés desktop/mobile188                continue189            seen.add(ext_id)190            bedrooms = None191            bm = BED_RE.search(blob.split("À partir")[0])192            if bm:193                bedrooms = float(bm.group(1))194            price_label = (f"À partir de {lo:.0f} $"195                           + (f" jusqu'à {hi:.0f} $" if hi else "")196                           + " /mois tout inclus")197            listings.append(Listing(198                source=self.source_id,199                external_id=ext_id,200                url=PAGE_URL,201                title=f"{unit_type} — OCartier 2, appartements locatifs à Laval",202                address=ADDRESS,203                sector=SECTOR,204                city=CITY,205                unit_type=unit_type,206                bedrooms=bedrooms,207                price=lo,208                price_label=price_label,209                description=("OCartier 2 propose 200 appartements locatifs "210                             "haut de gamme à Laval, du studio au 5½, à deux "211                             "pas du métro Cartier. Prix tout inclus : "212                             "électricité, chauffage, climatisation, eau et "213                             "internet."),214                amenities=list(BUILDING_AMENITIES),215                images=images,216            ))217        return listings218
Files main
Menu

Theme