SPB Git

Repository Public

lambert.py 7.6 KB 200 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/lambert.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/lambert.py : connecteur Société Immobilière Lambert91#   (lambertimmobilier.com — Louiseville, Yamachiche, Mauricie). WordPress92#   avec thème custom « cognitif-starter » : la page /logements-disponibles/93#   liste des <article class="apartment"> (type h2, prix, <address>, photo en94#   background-image). On ne garde que la section « Nos logements à louer »95#   (les <article> suivant le titre « Projets à venir » = terrains, exclus).96#   Aucune page détail ; external_id = slug de l'adresse. 1 requête par sync.97# -----------------------------------------------------------------------------98from __future__ import annotations99100import re101import unicodedata102103from bs4 import BeautifulSoup104105from ..schema import Listing, normalize_unit_type, parse_price106from .base import BaseConnector107108BASE = "https://lambertimmobilier.com"109LIST_URL = f"{BASE}/logements-disponibles/"110111_BG_URL_RE = re.compile(r"background-image\s*:\s*url\(['\"]?([^'\")]+)")112_CITIES = [113    ("louiseville", "Louiseville"),114    ("yamachiche", "Yamachiche"),115    ("trois-rivieres", "Trois-Rivières"),116]117118119def _strip_accents(s: str) -> str:120    return "".join(c for c in unicodedata.normalize("NFD", s)121                   if unicodedata.category(c) != "Mn")122123124def _slug(s: str) -> str:125    s = _strip_accents(s.lower())126    return re.sub(r"[^a-z0-9]+", "-", s).strip("-")127128129class LambertConnector(BaseConnector):130    source_id = "lambert"131    request_delay = 0.7132133    def fetch(self) -> list[Listing]:134        html = self.get(LIST_URL).text135        soup = BeautifulSoup(html, "html.parser")136        listings: dict[str, Listing] = {}137        in_projects = False138        for el in soup.find_all(["h1", "h2", "article"]):139            if el.name in ("h1", "h2"):140                txt = el.get_text(" ", strip=True)141                if re.search(r"projets? à venir", txt, re.I):142                    in_projects = True        # terrains/projets : hors annonces143                continue144            if in_projects or "apartment" not in (el.get("class") or []):145                continue146            try:147                self._parse_card(el, listings)148            except Exception:149                continue150        return list(listings.values())151152    def _parse_card(self, card, listings: dict[str, Listing]) -> None:153        head = card.select_one("h2")154        head_txt = re.sub(r"\s+", " ", head.get_text(" ", strip=True)) if head else ""155        if re.search(r"terrain|commercial|local\b", head_txt, re.I):156            return157        addr_el = card.find("address")158        address_full = re.sub(r"\s+", " ",159                              addr_el.get_text(" ", strip=True)) if addr_el else ""160        if not address_full and not head_txt:161            return162163        # ville en fin d'adresse (« 131 St-Ubald Louiseville »)164        city, address = "", address_full165        low = _strip_accents(address_full.lower())166        for key, name in _CITIES:167            if key in low:168                city = name169                address = re.sub(rf",?\s*{key}\s*$", "", address_full,170                                 flags=re.I).strip(" ,")171                break172173        price_el = card.select_one(".apartment--price")174        price_label = re.sub(r"\s+", " ",175                             price_el.get_text(" ", strip=True)) if price_el else ""176177        images: list[str] = []178        img_div = card.select_one("div.img[style]")179        if img_div:180            m = _BG_URL_RE.search(img_div["style"])181            if m and m.group(1).startswith("http"):182                images.append(m.group(1))183184        ext = _slug(address_full or head_txt)185        if not ext or ext in listings:186            return187        title = f"{head_txt} — {address_full}" if head_txt else address_full188        listings[ext] = Listing(189            source=self.source_id,190            external_id=ext,191            url=LIST_URL,192            title=title,193            address=address,194            city=city,195            unit_type=normalize_unit_type(head_txt),196            price=parse_price(price_label),197            price_label=price_label,198            images=images,199        )200
Files main
Menu

Theme