SPB Git

Repository Public

desroches.py 8.5 KB 215 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/desroches.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/desroches.py : connecteur Immeubles Claude Desroches91#   (immeublesclaudedesroches.com — Granby, Cowansville, Drummondville).92#   Site PHP custom : une seule page statique /logements-a-louer/ avec un93#   tableau par ville (« Nos logements à louer à <Ville> ») ; une ligne par94#   logement, repérée par son ancre stable <a name="logNN">. Colonnes :95#   photo (badge est-loue.png = déjà loué -> ignoré), adresse, grandeur,96#   prix, étage, note libre (mois de libération, inclusions, rénové…).97#   La section « LOCAUX À LOUER » (commercial) n'a pas d'ancres logNN et98#   est donc naturellement exclue. Aucune page détail n'existe.99# -----------------------------------------------------------------------------100from __future__ import annotations101102import re103104from bs4 import BeautifulSoup105106from ..schema import Listing, normalize_unit_type, parse_price107from .base import BaseConnector108109BASE = "https://www.immeublesclaudedesroches.com"110LIST_URL = f"{BASE}/logements-a-louer/"111112_ANCHOR_RE = re.compile(r"^log\d+$")113_CITY_RE = re.compile(r"logements à louer à\s+([A-Za-zÀ-ÿ' -]+)", re.I)114115# segments de la note libre qui parlent de disponibilité (mois ou « libre ») —116# le reste (« rénové », « chauffé », « Ascenseur »…) n'est pas une date et117# fausserait la normalisation centrale118_AVAIL_SEG_RE = re.compile(119    r"\b(janvier|f[ée]vrier|mars|avril|mai|juin|juillet|ao[ûu]t|septembre|"120    r"octobre|novembre|d[ée]cembre|libre|maintenant)\b", re.I)121122123def _availability_from_note(note: str) -> str:124    """Ne garde de la note que les segments de disponibilité (« juillet »,125    « libre »…) ; « rénové, juillet » -> « juillet »."""126    segs = [s.strip() for s in re.split(r"[,;]", note or "")]127    return ", ".join(s for s in segs if s and _AVAIL_SEG_RE.search(s))128129130class DesrochesConnector(BaseConnector):131    source_id = "desroches"132    request_delay = 0.6133134    def fetch(self) -> list[Listing]:135        html = self.get(LIST_URL).text136        soup = BeautifulSoup(html, "html.parser")137138        listings: dict[str, Listing] = {}139        for anchor in soup.find_all("a", attrs={"name": _ANCHOR_RE}):140            try:141                lst = self._parse_row(anchor)142            except Exception:143                continue144            if lst and lst.external_id not in listings:145                listings[lst.external_id] = lst146        return list(listings.values())147148    # -- ligne du tableau -----------------------------------------------------------149    def _parse_row(self, anchor) -> Listing | None:150        row = anchor.find_parent("tr")151        if row is None:152            return None153154        # badge « est loué » superposé à la photo -> logement non offert155        if row.find("img", src=re.compile(r"est-loue", re.I)):156            return None157158        # ville : plus proche en-tête « Nos logements à louer à <Ville> »159        # avant la ligne (les tableaux sont groupés par ville)160        city = ""161        for prev in anchor.find_all_previous(["p", "h1"]):162            t = " ".join(prev.get_text(" ", strip=True).split())163            m = _CITY_RE.search(t)164            if m:165                city = m.group(1).strip()166                break167        if not city:168            return None169170        cells = [" ".join(td.get_text(" ", strip=True).split())171                 for td in row.find_all("td")]172        # [photo, adresse, grandeur, prix, étage, note]173        if len(cells) < 4:174            return None175        address_raw = cells[1] if len(cells) > 1 else ""176        size_raw = cells[2] if len(cells) > 2 else ""177        price_raw = cells[3] if len(cells) > 3 else ""178        floor_raw = cells[4] if len(cells) > 4 else ""179        note_raw = cells[5] if len(cells) > 5 else ""180        if not address_raw:181            return None182183        amenities = []184        if floor_raw:185            amenities.append(f"Étage : {floor_raw}")186187        # photo réelle (default.png = image de remplacement, ignorée)188        images = []189        for img in row.find_all("img", src=True):190            src = img["src"]191            if re.search(r"est-loue|default\.png", src, re.I):192                continue193            src = re.sub(r"^(\.\./)+", "/", src)194            if not src.startswith("http"):195                src = BASE + (src if src.startswith("/") else f"/{src}")196            if src not in images:197                images.append(src)198199        ext_id = anchor.get("name")200        return Listing(201            source=self.source_id,202            external_id=ext_id,203            url=f"{LIST_URL}#{ext_id}",204            title=f"{address_raw}, {city}",205            address=f"{address_raw}, {city}",206            city=city,207            unit_type=normalize_unit_type(size_raw),208            price=parse_price(price_raw),209            price_label=price_raw,210            availability=_availability_from_note(note_raw),   # « juillet », …211            description=note_raw,           # note libre : inclusions, rénové…212            amenities=amenities,213            images=images[:5],214        )215
Files main
Menu

Theme