SPB Git

Repository Public

ascensio.py 11.2 KB 275 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/ascensio.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/ascensio.py : connecteur Groupe Ascensio (groupeascensio.com)91#   Société immobilière — logements neufs à Sherbrooke (Les Nations :92#   arrondissements Jacques-Cartier et Mont-Bellevue) + Pont-Rouge (région de93#   Québec). WordPress : la page /logements-a-louer/ est rendue serveur —94#   grille `.grid-logements .grid-item` (une carte par logement disponible :95#   type + numéro, date de disponibilité, secteur, immeuble, photo, lien96#   /location/<slug>/). Les fiches (via self.detail, cache BD) ajoutent le97#   numéro de référence stable (external_id, ex. BRY-2030134), la mensualité,98#   la description, les pièces et dimensions et la galerie. Seuls les99#   logements affichés (tous « Disponible ») deviennent des annonces.100# -----------------------------------------------------------------------------101from __future__ import annotations102103import hashlib104import re105106from bs4 import BeautifulSoup107108from ..schema import Listing, normalize_unit_type, parse_price109from .base import BaseConnector110111BASE = "https://groupeascensio.com"112LIST_URL = f"{BASE}/logements-a-louer/"113114_VARIANT_IMG = re.compile(r"-\d{2,4}x\d{2,4}(?=\.(?:jpg|jpeg|png|webp)$)", re.I)115116117class AscensioConnector(BaseConnector):118    source_id = "ascensio"119    request_delay = 0.6120    max_details = 40      # garde-fou fiches détail (vraies requêtes)121122    def fetch(self) -> list[Listing]:123        html = self.get(LIST_URL).text124        soup = BeautifulSoup(html, "html.parser")125126        listings: dict[str, Listing] = {}127        for card in soup.select(".grid-logements .grid-item"):128            try:129                lst = self._parse_card(card)130            except Exception:131                continue132            if lst and lst.external_id not in listings:133                listings[lst.external_id] = lst134135        # fiches détail (cache BD) : référence, mensualité, description,136        # pièces/dimensions, galerie137        self._fetched = 0138        out: dict[str, Listing] = {}139        for slug, lst in listings.items():140            key = hashlib.sha1(141                f"{lst.title}|{lst.availability}|{lst.sector}"142                .encode("utf-8")).hexdigest()143            try:144                payload = self.detail(slug, key,145                                      lambda u=lst.url: self._fetch_detail(u))146            except Exception:147                payload = {}148            self._apply_detail(lst, payload)149            # référence de gestion stable (BRY-2030134) quand publiée150            ref = (payload.get("reference") or "").strip()151            lst.external_id = ref or slug152            if lst.external_id not in out:153                out[lst.external_id] = lst154        return list(out.values())155156    # -- carte de la grille -----------------------------------------------------------157    def _parse_card(self, card) -> Listing | None:158        link = card.select_one("a[href*='/location/']")159        if not link:160            return None161        url = link["href"]162        m = re.search(r"/location/([^/]+)/?", url)163        if not m:164            return None165        slug = m.group(1)166167        title_el = card.select_one(".logement-title")168        title = re.sub(r"\s+", " ",169                       title_el.get_text(" ", strip=True)).strip() if title_el else slug170171        # « Disponibilité : 01/08/2026 » (bandeau survol)172        availability = ""173        extra = card.select_one(".extra-infos")174        if extra:175            m2 = re.search(r"Disponibilit[eé]\s*:?\s*([\d/]+)",176                           extra.get_text(" ", strip=True))177            if m2:178                availability = f"Disponible le {m2.group(1)}"179180        sector_el = card.select_one(".secteur-title")181        sector = ""182        if sector_el:183            sector = re.sub(r"^\s*Secteur\s*:?\s*", "",184                            sector_el.get_text(" ", strip=True)).strip(" .")185186        imm_el = card.select_one(".immeuble-value")187        immeuble = re.sub(r"\s+", " ",188                          imm_el.get_text(" ", strip=True)).strip() if imm_el else ""189190        # ville réelle : Sherbrooke, sauf mention explicite de Pont-Rouge191        city = "Pont-Rouge" if re.search(r"pont-rouge", sector, re.I) else "Sherbrooke"192193        unit_type = normalize_unit_type(title)194        if not re.fullmatch(r"\d½\+?|6½\+|Studio|Loft|Chambre|Maison",195                            unit_type or ""):196            unit_type = ""197198        img = card.select_one("img[src]")199        images = []200        if img and str(img.get("src", "")).startswith("http"):201            images.append(_VARIANT_IMG.sub("", img["src"]))202203        amenities = [f"Immeuble : {immeuble}"] if immeuble else []204        return Listing(205            source=self.source_id,206            external_id=slug,          # remplacé par la référence en aval207            url=url,208            title=f"{title} — {immeuble}" if immeuble else title,209            address=immeuble if re.match(r"^\d", immeuble) else "",210            sector=sector,211            city=city,212            unit_type=unit_type,213            availability=availability,214            amenities=amenities,215            images=images,216        )217218    # -- fiche logement ---------------------------------------------------------------219    def _fetch_detail(self, url: str) -> dict:220        if self._fetched >= self.max_details:221            raise RuntimeError("budget de fiches détail atteint")222        self._fetched += 1223        html = self.get(url).text224        soup = BeautifulSoup(html, "html.parser")225        out: dict = {}226227        # paires h5 -> valeur : Référence, Mensualité, Disponibilités228        for h in soup.select("h5"):229            lab = h.get_text(" ", strip=True).lower()230            sib = h.find_next_sibling()231            if sib is None:232                continue233            val = re.sub(r"\s+", " ", sib.get_text(" ", strip=True)).strip()234            if "référence" in lab or "reference" in lab:235                out["reference"] = val236            elif "mensualité" in lab or "mensualite" in lab:237                out["price_label"] = val238            elif "disponibilités" in lab or "disponibilites" in lab:239                out["availability"] = val240            elif "pièces et dimensions" in lab and sib.name == "ul":241                out["rooms"] = [re.sub(r"\s+", " ", li.get_text(" ", strip=True))242                                for li in sib.select("li")][:15]243244        # description : paragraphes longs du corps de la fiche245        paras = [re.sub(r"\s+", " ", p.get_text(" ", strip=True))246                 for p in soup.select("p")]247        longs = [p for p in paras if len(p) > 120]248        if longs:249            out["description"] = " ".join(longs)[:1500]250251        images: list[str] = []252        for img in soup.select("img[src*='/wp-content/uploads/']"):253            src = _VARIANT_IMG.sub("", str(img.get("src") or ""))254            if src.startswith("http") and src not in images \255                    and not re.search(r"logo|icon|favicon", src, re.I):256                images.append(src)257        out["images"] = images[:20]258        return out259260    def _apply_detail(self, lst: Listing, d: dict) -> None:261        if not d:262            return263        if d.get("price_label"):264            lst.price_label = d["price_label"]           # « 1425 $ / mois »265            lst.price = parse_price(re.sub(r"(\d)\s(\d{3})", r"\1\2",266                                           d["price_label"]))267        if d.get("availability"):268            lst.availability = d["availability"]269        if d.get("description"):270            lst.description = d["description"]271        if d.get("rooms"):272            lst.amenities = list(dict.fromkeys(lst.amenities + d["rooms"]))273        if d.get("images"):274            lst.images = list(dict.fromkeys(d["images"] + lst.images))[:20]275
Files main
Menu

Theme