SPB Git

Repository Public

excell.py 10.5 KB 260 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/excell.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/excell.py : Les immeubles EXCELL (immeublesexcell.com) — agence91#   immobilière d'Abitibi-Ouest (La Sarre, Macamic, Taschereau…) avec une92#   section « Logements » à louer.93#   Techno : ColdFusion servi côté serveur (details.cfm?LogementID=N) — simple94#   parse HTML des cartes `ficheMaison` + page détail pour les attributs95#   (type, meublé, animaux, chauffage, électroménagers, étage).96#   Granularité : LOGEMENT (une carte = un logement, LogementID stable).97# -----------------------------------------------------------------------------98from __future__ import annotations99100import hashlib101import html as _html102import re103104import requests105106from .base import BaseConnector107from ..schema import Listing108109BASE = "https://www.immeublesexcell.com"110LIST_URL = f"{BASE}/fr/logements/"111112_CARD_SPLIT_RE = re.compile(r'<div class="ficheMaison">')113_ID_RE = re.compile(r'LogementID_(\d+)')114_PRICE_RE = re.compile(r'<h4>([^<]+)</h4>')115_ADDR_RE = re.compile(r'<p>\s*([^<]+?)<br')116_IMG_RE = re.compile(r'background:url\(([^)]+)\)')117# attributs « <span class="valeurAttribut">X</span>…<span class="valeurAttributDetails">Y</span> »118_ATTR_RE = re.compile(119    r'<span class="valeurAttribut">([^<]*)</span>\s*<br\s*/?>\s*'120    r'(?:<span class="valeurAttributDetails">)?([^<]*)', re.S)121_POSTAL_RE = re.compile(r'\b[A-Za-z]\d[A-Za-z]\s?\d[A-Za-z]\d\b')122_DETAIL_IMG_RE = re.compile(r'(?:src|href)="([^"]*images/logements[^"]*)"')123124# labels détail -> clés structurées125_DETAIL_KEYS = {"type", "mobilié", "mobilier", "chauffage", "animaux",126                "étage", "frigidaire", "laveuse", "sécheuse", "extérieur",127                "poêle", "lave-vaisselle"}128129130def _abs(url: str) -> str:131    url = url.strip().strip("'\"")132    if url.startswith("http"):133        return url134    return BASE + "/" + url.lstrip("./").lstrip("/")135136137class ExcellConnector(BaseConnector):138    """Les immeubles EXCELL — logements à louer en Abitibi-Ouest."""139140    source_id = "excell"141    request_delay = 0.8142143    def _parse_detail(self, ext_id: str) -> dict:144        """Attributs de la page détail (dict JSON-sérialisable, pour cache)."""145        url = f"{LIST_URL}details.cfm?LogementID={ext_id}"146        h = re.sub(r"\s+", " ", self.get(url).text)147        attrs: dict[str, str] = {}148        for k, v in _ATTR_RE.findall(h):149            k, v = _html.unescape(k).strip(), _html.unescape(v).strip()150            if k and v and k.lower() in _DETAIL_KEYS | {"location"}:151                attrs[k] = v152        images = [_abs(u) for u in _DETAIL_IMG_RE.findall(h)]153        return {"attrs": attrs, "images": images}154155    def fetch(self) -> list[Listing]:156        page = self.get(LIST_URL).text157        out: list[Listing] = []158        seen: set[str] = set()159        for block in _CARD_SPLIT_RE.split(page)[1:]:160            b = re.sub(r"\s+", " ", block)161            m = _ID_RE.search(b)162            if not m:163                continue164            ext_id = m.group(1)165            if ext_id in seen:166                continue167            seen.add(ext_id)168            url = f"{LIST_URL}details.cfm?LogementID={ext_id}"169170            price_m = _PRICE_RE.search(b)171            price_label = _html.unescape(price_m.group(1)).strip() if price_m else ""172            addr_m = _ADDR_RE.search(b)173            raw_addr = _html.unescape(addr_m.group(1)).strip() if addr_m else ""174            raw_addr = _POSTAL_RE.sub("", raw_addr).strip(" ,")175            parts = [p.strip() for p in raw_addr.split(",") if p.strip()]176            city = parts[-1] if len(parts) > 1 else ""177            address = ", ".join(parts[:-1]) if len(parts) > 1 else raw_addr178179            # attributs de la carte : pièces (5 1/2), chambres, sdb, dispo180            unit_type, bedrooms, bathrooms, avail = "", None, None, ""181            for val, lbl in _ATTR_RE.findall(b):182                val = _html.unescape(val).strip()183                lbl = _html.unescape(lbl).strip()184                low = lbl.lower()185                if "pièce" in low and val:186                    unit_type = val187                elif "chambre" in low and val:188                    try:189                        bedrooms = float(val)190                    except ValueError:191                        pass192                elif "bain" in low and val:193                    try:194                        bathrooms = float(val)195                    except ValueError:196                        pass197                elif not val and lbl:        # icône calendrier : début location198                    avail = lbl199200            imgs: list[str] = []201            img_m = _IMG_RE.search(b)202            if img_m and "no-image" not in img_m.group(1):203                imgs.append(_abs(img_m.group(1)))204205            # page détail (cache : clé = hash de la carte)206            key = hashlib.sha256(b.encode()).hexdigest()[:16]207            try:208                det = self.detail(ext_id, key,209                                  lambda e=ext_id: self._parse_detail(e))210            except requests.RequestException:211                det = {}212            attrs = det.get("attrs") or {}213            for u in det.get("images") or []:214                if u not in imgs:215                    imgs.append(u)216217            # filtre résidentiel : le site ne liste que des logements ;218            # on écarte tout de même les locaux commerciaux éventuels219            typ = (attrs.get("Type") or "").lower()220            if typ and any(w in typ for w in ("commercial", "bureau", "local",221                                              "entrepôt", "garage")):222                continue223224            furnished = None225            mob = (attrs.get("Mobilié") or attrs.get("Mobilier") or "").lower()226            if mob:227                furnished = "meublé" in mob and "non" not in mob228            pets = None229            ani = (attrs.get("Animaux") or "").lower()230            if ani:231                pets = "oui" if ani.startswith("oui") else \232                       "non" if ani.startswith("non") else "conditions"233234            if "chambre" in typ:                # chambre en maison de chambres235                unit_type = "Chambre"236237            amenities = [f"{k} : {v}" for k, v in attrs.items()238                         if k.lower() in _DETAIL_KEYS]239            avail = attrs.get("Location") or avail240241            out.append(Listing(242                source=self.source_id,243                external_id=ext_id,             # LogementID ColdFusion (stable)244                url=url,245                title=f"{address}, {city}".strip(" ,"),246                address=address,247                city=city,248                unit_type=unit_type,249                bedrooms=bedrooms,250                bathrooms=bathrooms,251                price_label=price_label,        # ex. « 975 $ / mois »252                availability=f"Location : {avail}" if avail else "",253                furnished=furnished,254                pets=pets,255                amenities=amenities,256                details={"region": "Abitibi-Témiscamingue"},257                images=imgs[:30],258            ))259        return out260
Files main
Menu

Theme