SPB Git

Repository Public

dupin_despres.py 11.2 KB 277 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/dupin_despres.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/dupin_despres.py : connecteur Dupin Després (dupindespres.com)91#   Gestionnaire de Repentigny / Rive-Nord (Les Cimes Repentigny, Quartier du92#   Moulin, immeubles rue Notre-Dame…). WordPress (thème d'agence « Voyou »,93#   classes vy_*) rendu serveur : /appartements-a-louer + /page/N liste des94#   cartes par UNITÉ (titre, typologie, ville, prix, bandeau de disponibilité,95#   badge 55 ans+). La page détail fournit description, photos et l'adresse96#   civique (fil d'Ariane JSON-LD, ex. « #118-325 rue Notre-Dame Repentigny »).97#   Granularité : unité.98# -----------------------------------------------------------------------------99from __future__ import annotations100101import json102import re103104from bs4 import BeautifulSoup105106from ..schema import Listing, normalize_unit_type107from .base import BaseConnector108109BASE = "https://dupindespres.com"110LIST_URL = f"{BASE}/appartements-a-louer"111MAX_PAGES = 10112113IMG_RE = re.compile(114    r"https://dupindespres\.com/app/uploads/[^\"'\s\\]+\.(?:jpe?g|png|webp)", re.I)115SKIP_IMG_RE = re.compile(r"logo|favicon|icon|-\d{2,4}x\d{2,4}\.", re.I)116PHONE_RE = re.compile(r"(\d{3})\s*(\d{3})[\s-]*(\d{4})")117# dernier maillon du fil d'Ariane JSON-LD : « #118-325 rue Notre-Dame Repentigny »118CRUMB_RE = re.compile(r'"name"\s*:\s*"(#[^"]+)"')119120121class DupinDespresConnector(BaseConnector):122    source_id = "dupin_despres"123    request_delay = 0.8124    max_images = 12125126    # -- page détail (cachée en BD via self.detail) ---------------------------127    def _detail(self, url: str) -> dict:128        try:129            html = self.get(url).text130        except Exception:131            return {}132        soup = BeautifulSoup(html, "html.parser")133        payload: dict = {}134135        # adresse : dernier maillon du fil d'Ariane JSON-LD (« #118-325 rue … »)136        for script in soup.find_all("script", type="application/ld+json"):137            m = CRUMB_RE.findall(script.string or "")138            if m:139                addr = json.loads(f'"{m[-1]}"') if "\\" in m[-1] else m[-1]140                # « #118-325 rue Notre-Dame Repentigny » -> « 325 rue Notre-Dame »141                addr = re.sub(r"^#?\d+\s*-\s*", "", addr).strip()142                payload["address"] = addr143                break144145        # description : paragraphes du corps de la fiche146        body = soup.select_one(".vy_main_body")147        if body is not None:148            paras = [re.sub(r"\s+", " ", p.get_text(" ", strip=True))149                     for p in body.find_all("p")]150            desc = " ".join(t for t in paras if len(t) > 40)151            if desc:152                payload["description"] = desc[:1500]153154        # contact (téléphone affiché sur la fiche)155        m = re.search(r'href="tel:\+?1?(\d{10})"', html)156        if m:157            d = m.group(1)158            payload["phone"] = f"{d[:3]}-{d[3:6]}-{d[6:]}"159160        # photos de la fiche161        imgs = [u for u in dict.fromkeys(IMG_RE.findall(html))162                if not SKIP_IMG_RE.search(u)]163        payload["images"] = imgs[: self.max_images]164        return payload165166    # -- fetch -----------------------------------------------------------------167    def fetch(self) -> list[Listing]:168        listings: list[Listing] = []169        seen: set[str] = set()170171        for page in range(1, MAX_PAGES + 1):172            url = LIST_URL if page == 1 else f"{LIST_URL}/page/{page}"173            try:174                html = self.get(url).text175            except Exception:176                break177            soup = BeautifulSoup(html, "html.parser")178            items = soup.select(".vy_rentals_listing_item")179            if not items:180                break181182            new_on_page = 0183            for it in items:184                link = it.select_one("a.vy_link_cover[href]")185                if link is None:186                    continue187                href = link["href"].split("?")[0].rstrip("/")188                slug = href.rsplit("/", 1)[-1]189                if not slug or "/page/" in href or slug in seen:190                    continue191                seen.add(slug)192                new_on_page += 1193194                title = ""195                el = it.select_one(".vy_rentals_listing_item_title")196                if el is not None:197                    title = re.sub(r"\s+", " ", el.get_text(" ", strip=True))198199                # <span>4 ½</span> | <span>Repentigny</span> — certaines cartes200                # n'ont pas de span typologie (ex. Les Cimes Saint-Sulpice)201                unit_type = city = ""202                info = it.select_one(".vy_rentals_listing_item_info")203                if info is not None:204                    spans = [s.get_text(" ", strip=True)205                             for s in info.find_all("span")]206                    for s in (s for s in spans if s):207                        if re.search(r"½|1/2|studio|loft|chambre", s, re.I):208                            unit_type = normalize_unit_type(s)209                        else:210                            city = s211212                price = None213                price_label = ""214                el = it.select_one(".vy_rentals_listing_item_price")215                if el is not None:216                    price_label = el.get_text(" ", strip=True)217                    m = re.search(r"(\d[\d\s,]*)\s*\$", price_label)218                    if m:219                        try:220                            val = float(m.group(1).replace(" ", "")221                                        .replace(" ", "").replace(",", ""))222                            if 300 <= val <= 20000:223                                price = val224                        except ValueError:225                            pass226227                availability = ""228                el = it.select_one(".vy_bannerinfo_text")229                if el is not None:230                    availability = el.get_text(" ", strip=True)231232                amenities: list[str] = []233                if it.select_one(".vy_badge.--fiftyfive") is not None:234                    amenities.append("55 ans et plus")235236                card_img = ""237                img = it.select_one("img[data-src]")238                if img is not None:239                    card_img = img.get("data-src") or ""240241                key = f"{unit_type}|{city}|{price_label}|{availability}"242                det = self.detail(slug, key, lambda u=href: self._detail(u))243244                images = list(det.get("images") or [])245                if card_img and card_img not in images:246                    images.insert(0, card_img)247                details: dict = {}248                if det.get("phone"):249                    details["contact"] = {"phone": det["phone"]}250251                # adresse : fiche détail, sinon dérivée du slug de l'URL252                address = det.get("address") or ""253                if not address:254                    m = re.match(r"^\d+-(.+?)(?:-repentigny|-terrebonne)?$", slug)255                    if m and re.search(r"[a-z]{3}", m.group(1)):256                        address = m.group(1).replace("-", " ")257258                listings.append(Listing(259                    source=self.source_id,260                    external_id=slug,261                    url=href,262                    title=title or f"Appartement {unit_type}",263                    address=address,264                    city=city,265                    unit_type=unit_type,266                    price=price,267                    price_label=price_label,268                    availability=availability,269                    description=det.get("description", ""),270                    amenities=amenities,271                    details=details,272                    images=images[: self.max_images],273                ))274            if new_on_page == 0:275                break276        return listings277
Files main
Menu

Theme