SPB Git

Repository Public

c3r.py 9.2 KB 227 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/c3r.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-2513# Last Modified    : 2026-09-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/c3r.py : connecteur Gestion C3R (gestionc3r.com)91#   Gestionnaire de la Mauricie (Trois-Rivières, Shawinigan, Saint-Boniface,92#   Saint-Maurice). Refonte du site le 2026-09-08 : l'ancien site Wix (et son93#   API wix-data, collections Import1/Import2) a été remplacé par un site94#   statique Astro servi par Express — les collections n'existent plus95#   (WDE0025) et les anciennes URLs redirigent vers /logements.96#   Nouveau modèle : catalogue /logements?page=N paginé côté serveur97#   (~18 cartes/page, 73 unités, 4 projets), chaque carte <article98#   data-rental-unit> porte des attributs data-* propres (city, project,99#   bedrooms, price, status) + type, adresse, salle de bain, superficie et100#   photo dans le corps de la carte. Seul le statut « Disponible » est gardé101#   (Loué / Réservé : non). Granularité : une annonce par unité.102# -----------------------------------------------------------------------------103from __future__ import annotations104105import re106107from bs4 import BeautifulSoup108109from ..schema import Listing, normalize_unit_type110from .base import BaseConnector111112BASE = "https://www.gestionc3r.com"113LIST_URL = f"{BASE}/logements"114115# seul « Disponible » = louable maintenant (Réservé / Loué : non)116KEEP_STATUS = {"disponible"}117118MAX_PAGES = 20  # 5 pages au lancement (2026-09-08) — marge de croissance119120121def _num(raw: str | None) -> float | None:122    """Premier nombre d'un texte (« 1 575 $/mois », « 1100 pi² ») → float."""123    if raw is None:124        return None125    digits = re.sub(r"[^\d,.]", "", str(raw)).replace(",", ".")126    m = re.match(r"\d+(?:\.\d+)?", digits)127    return float(m.group(0)) if m else None128129130class C3RConnector(BaseConnector):131    source_id = "c3r"132    request_delay = 0.7133134    def fetch(self) -> list[Listing]:135        listings: list[Listing] = []136        seen: set[str] = set()137        cards_total = 0138139        for page in range(1, MAX_PAGES + 1):140            params = {"page": page} if page > 1 else None141            # le serveur n'annonce pas de charset → requests décoderait en142            # latin-1 (« Loué ») ; la page déclare <meta charset="utf-8">143            html = self.get(LIST_URL, params=params).content.decode(144                "utf-8", errors="replace")145            soup = BeautifulSoup(html, "html.parser")146            cards = soup.select("article[data-rental-unit]")147            if not cards:148                break149150            new_on_page = 0151            for card in cards:152                link = card.select_one("a[href]")153                href = (link.get("href") or "").strip() if link else ""154                slug = href.rstrip("/").split("/")[-1] if href else ""155                ext_id = slug or ""156                if not ext_id or ext_id in seen:157                    continue  # au-delà de la dernière page, le site re-sert158                seen.add(ext_id)  # la même page → dédup par slug159                new_on_page += 1160                cards_total += 1161162                status = (card.get("data-status") or "").strip()163                if status.lower() not in KEEP_STATUS:164                    continue165166                city = (card.get("data-city") or "").strip()167                price = _num(card.get("data-price"))168                beds = _num(card.get("data-bedrooms"))169170                el = card.select_one(".rental-card__type")171                unit_type = normalize_unit_type(172                    el.get_text(strip=True) if el else "")173                el = card.select_one("h3")174                title = el.get_text(" ", strip=True) if el else ext_id175                el = card.select_one(".rental-card__location")176                address = el.get_text(" ", strip=True) if el else ""177                el = card.select_one(".rental-card__eyebrow span")178                project = el.get_text(" ", strip=True) if el else ""179180                baths = area = None181                for fact in card.select(".rental-card__facts > div"):182                    dt = fact.select_one("dt span")183                    dd = fact.select_one("dd")184                    if not dt or not dd:185                        continue186                    label = dt.get_text(strip=True).lower()187                    if "salle" in label:188                        baths = _num(dd.get_text())189                    elif "superficie" in label:190                        area = _num(dd.get_text())191192                img = card.select_one(".rental-card__media img[src]")193                images = [img["src"].split("#")[0]] if img else []194195                details: dict = {}196                if project:197                    details["project"] = project198199                listings.append(Listing(200                    source=self.source_id,201                    external_id=ext_id,202                    url=f"{BASE}{href}" if href.startswith("/") else href,203                    title=f"{unit_type or 'Appartement'} — {title}",204                    address=address,205                    city=city,206                    unit_type=unit_type,207                    bedrooms=beds,208                    bathrooms=baths,209                    price=price,210                    availability=status,211                    area_sqft=area,212                    details=details,213                    images=images,214                ))215216            if new_on_page == 0:217                break218219        if cards_total == 0:220            # une page catalogue saine contient toujours des cartes (tous221            # statuts confondus) — 0 carte = rendu partiel ou structure222            # changée : échec franc plutôt qu'un faux « 0 trouvé ok »223            raise RuntimeError(224                "c3r : aucune carte data-rental-unit parsée sur "225                f"{LIST_URL} — structure changée ?")226        return listings227
Files main
Menu

Theme