SPB Git

Repository Public

leclif.py 10.2 KB 247 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/leclif.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-0613# 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/leclif.py : connecteur Le Clif (leclif.ca)91#   Projet mono-immeuble de 151 condos locatifs à Charlesbourg (Québec).92#   Toutes les unités sont dans la page d'accueil (overlays « is-overlay-N »);93#   les unités louées sont marquées par un script jQuery addClass('non-dispo').94#   La page fournit aussi la liste des avantages de l'immeuble95#   (ul.liste-icones : inclusions, piscine, gym, politique animaux…) et le96#   lien Google Maps (lat/lng).97# -----------------------------------------------------------------------------98from __future__ import annotations99100import re101102from bs4 import BeautifulSoup103104from ..schema import Listing, infer_city, normalize_unit_type, parse_price105from .base import BaseConnector106107BASE = "https://leclif.ca"108SECTOR = "Charlesbourg"109ADDRESS = "19700, boul. Henri-Bourassa, Québec, G1G 0L1"110111# lat/lng du lien « Voir sur la carte » (…!3d46.8934679!4d-71.2986717…)112_LATLNG_RE = re.compile(r"!3d(-?\d+\.\d+)!4d(-?\d+\.\d+)")113_SQFT_RE = re.compile(r"([\d\s  ,.]+?)\s*pi\s*2?", re.I)114115116def _extract_price(label: str) -> float | None:117    """'À partir de 2366 (incluant électros) $ / mois' -> 2366.0"""118    m = re.search(r"(\d[\d\s  ]{2,})", label or "")119    if not m:120        return None121    return parse_price(m.group(1).strip() + "$")122123124class LeClifConnector(BaseConnector):125    source_id = "leclif"126    request_delay = 0.6127128    def fetch(self) -> list[Listing]:129        html = self.get(BASE + "/").text130131        # Unités marquées non disponibles par le script de la page132        non_dispo = set(re.findall(133            r"jQuery\('\.unite-(\d+)'\)\.addClass\('non-dispo'\)", html))134135        soup = BeautifulSoup(html, "html.parser")136137        # lat/lng depuis le lien Google Maps de l'immeuble138        lat = lng = None139        m = _LATLNG_RE.search(html)140        if m:141            lat, lng = float(m.group(1)), float(m.group(2))142143        # avantages de l'immeuble (« Eau chaude fournie », « Air climatisé144        # inclus », « Chiens et chats acceptés », piscine, gym, stationnement…)145        building_amenities: list[str] = []146        pets = None147        for li in soup.select("ul.liste-icones > li"):148            p = li.select_one("p.texte")149            if not p:150                continue151            label = " ".join(p.get_text(" ", strip=True).split())152            label = re.sub(r"\s+i$", "", label)   # icône info « i » du picto153            # politique animaux : l'infobulle détaille des conditions154            # (chiens selon étage/poids, deux chats maximum)155            if re.search(r"chiens|chats|animaux", label, re.I):156                tooltip = li.select_one(".is-description")157                tip_txt = tooltip.get_text(" ", strip=True) if tooltip else ""158                if re.search(r"condition|moins de \d+ lb|maximum", tip_txt, re.I):159                    pets = "conditions"160                    label += " (sous conditions)"161            if label and label not in building_amenities:162                building_amenities.append(label)163164        listings: list[Listing] = []165166        for overlay in soup.select("div.overlay-unite"):167            try:168                cls = " ".join(overlay.get("class", []))169                m = re.search(r"is-overlay-(\d+)", cls)170                if not m:171                    continue172                num = m.group(1)173                if num in non_dispo:174                    continue          # unité louée175176                price_el = overlay.select_one("h3.price")177                price_label = (price_el.get_text(" ", strip=True)178                               if price_el else "")179                price = _extract_price(price_label)180181                # Liste des caractéristiques : Disponibilité / Type / Modèle /182                # Superficie / Terrasse183                availability = unit_type = model = ""184                area_sqft = None185                av = re.search(r"Disponibilité\s*:\s*([\wéûà]+)",186                               overlay.get_text(" ", strip=True))187                if av:188                    availability = f"Disponible en {av.group(1)}"189                desc_parts: list[str] = []190                for li in overlay.select("ul.flex li"):191                    t = li.get_text(" ", strip=True)192                    if t.startswith("Disponibilité"):193                        availability = t.split(":", 1)[-1].strip()194                    elif t.startswith("Type"):195                        unit_type = normalize_unit_type(t.split(":", 1)[-1])196                    elif t.startswith("Modèle"):197                        model = t.split(":", 1)[-1].strip()198                    elif t.startswith("Superficie"):199                        # champ étiqueté distinct de la terrasse -> area_sqft200                        sm = _SQFT_RE.search(t.split(":", 1)[-1])201                        if sm:202                            try:203                                area_sqft = float(re.sub(r"[\s  ,]", "",204                                                         sm.group(1)))205                            except ValueError:206                                pass207                        desc_parts.append(re.sub(r"\s+", " ", t))208                    elif t.startswith("Terrasse"):209                        desc_parts.append(re.sub(r"\s+", " ", t))210                if model:211                    desc_parts.insert(0, f"Modèle {model}")212213                # Images : aperçu du plan (jpg) dans l'overlay214                images: list[str] = []215                for img in overlay.select("img[src]"):216                    src = img["src"]217                    if src.startswith("http") and re.search(218                            r"\.(?:jpg|jpeg|png|webp)$", src, re.I):219                        images.append(src)220                images = list(dict.fromkeys(images))221222                listings.append(Listing(223                    source=self.source_id,224                    external_id=f"unite-{num}",225                    url=f"{BASE}/#unite-{num}",226                    title=f"Le Clif — Unité {num}"227                          f"{' (' + unit_type + ')' if unit_type else ''}",228                    address=ADDRESS,229                    sector=SECTOR,230                    city=infer_city(SECTOR),231                    unit_type=unit_type,232                    price=price,233                    price_label=price_label,234                    availability=availability or "Disponible",235                    area_sqft=area_sqft,236                    pets=pets,237                    description=" | ".join(desc_parts),238                    amenities=list(building_amenities),239                    images=images,240                    lat=lat,241                    lng=lng,242                ))243            except Exception:244                continue245246        return listings247
Files main
Menu

Theme