SPB Git

Repository Public

douek.py 8.8 KB 221 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/douek.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-2513# Last Modified    : 2026-08-3014#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/douek.py : connecteur Douek Apartments (douek.ca)91#   Gestionnaire familial montréalais : Westmount, NDG, Côte-des-Neiges,92#   Plateau, Vieux-Montréal, Saint-Henri, Dollard-des-Ormeaux. Même gabarit93#   Rentsync que le Groupe Alfid, mais SANS API Lift System exposée : la94#   découverte se fait par les cartes « featured_property » de la page95#   d'accueil (/rent/<slug> + adresse), puis parsing des fiches /rent/<slug>96#   rendues serveur — le parsing des rangées div.suite (id stable via97#   #modal-suite-<id>, prix, photos par suite) est hérité d'AlfidConnector.98# -----------------------------------------------------------------------------99from __future__ import annotations100101import re102import time103104from bs4 import BeautifulSoup105106from ..schema import Listing107from .alfid import AlfidConnector, _clean, _GALLERY_RE108109SITE = "https://www.douek.ca"110111# Slug de la fiche -> quartier (immeubles montréalais seulement ; les adresses112# de Westmount et Dollard-des-Ormeaux portent déjà leur vraie ville)113_SECTORS = {114    "2235-Prudhomme-NDG": "Notre-Dame-de-Grâce",115    "6101-monkland-ave": "Notre-Dame-de-Grâce",116    "2120-van-horne-cote-des-neiges": "Côte-des-Neiges",117    "lofts-clark": "Plateau-Mont-Royal",118    "le-st-regis-275-saint-jacques": "Vieux-Montréal",119    "le-rolland": "Saint-Henri",120}121122_META_DESC_RE = re.compile(r'<meta name="description" content="([^"]*)"')123124125class DouekConnector(AlfidConnector):126    source_id = "douek"127    request_delay = 0.6128    max_buildings = 20           # garde-fou (9 immeubles à l'écriture)129130    def fetch(self) -> list[Listing]:131        # Un raté transitoire (vu 2026-08-30 ~10:00) produisait un faux132        # « 0 trouvé ok » (médiane 10) : retry de l'accueil (3 essais,133        # backoff 5/10 s) puis erreur franche plutôt qu'un zéro silencieux.134        buildings: dict[str, dict] = {}135        for attempt in range(3):136            try:137                home = self.get(f"{SITE}/").text138            except Exception:139                if attempt == 2:140                    raise141                home = ""142            soup = BeautifulSoup(home, "html.parser")143            # cartes d'immeubles de l'accueil : slug, nom, adresse144            for card in soup.select(".featured_property"):145                a = card.select_one('a[href*="/rent/"]')146                if not a:147                    continue148                slug = (a.get("href") or "").rstrip("/").split("/")[-1]149                if not slug or slug == "cities":150                    continue151                name_el = card.select_one(".building-name")152                addr_el = card.select_one(".building-address")153                buildings.setdefault(slug, {154                    "name": _clean(name_el.get_text(" ", strip=True)155                                   if name_el else slug),156                    "address": _clean(addr_el.get_text(" ", strip=True)157                                      if addr_el else ""),158                })159            if buildings:160                break161            if attempt < 2:162                time.sleep(5 * (attempt + 1))163        if not buildings:164            raise RuntimeError(165                "accueil douek.ca sans carte featured_property après 3 essais")166167        listings: list[Listing] = []168        errors = 0169        last_exc: Exception | None = None170        for i, (slug, meta) in enumerate(buildings.items()):171            if i >= self.max_buildings:172                break173            try:174                listings.extend(self._parse_rent_page(slug, meta))175            except Exception as exc:176                errors += 1177                last_exc = exc178        # tous les immeubles en erreur et rien récolté : erreur franche179        if not listings and last_exc is not None and errors:180            raise last_exc181        return listings182183    # -- fiche /rent/<slug> : suites rendues serveur -----------------------------184    def _parse_rent_page(self, slug: str, meta: dict) -> list[Listing]:185        url = f"{SITE}/rent/{slug}"186        html = self.get(url).text187        soup = BeautifulSoup(html, "html.parser")188189        name = meta.get("name") or slug190        address = meta.get("address") or ""191        # ville en fin d'adresse (« …, Westmount QC ») ; défaut Montréal192        city = "Montréal"193        m = re.search(r",\s*([^,]+?)\s+QC\s*$", address)194        if m:195            c = _clean(m.group(1))196            if c and c.lower() not in ("montreal", "montréal"):197                city = c198        sector = _SECTORS.get(slug, "")199200        dm = _META_DESC_RE.search(html)201        description = _clean(dm.group(1))[:600] if dm else ""202203        amenities = [el.get_text(" ", strip=True)204                     for el in soup.select(".amenity-holder")]205        amenities = [a for a in dict.fromkeys(amenities) if a][:25]206207        images: list[str] = []208        seen_files: set[str] = set()209        for u in _GALLERY_RE.findall(html):210            fname = u.rsplit("/", 1)[-1]211            if fname not in seen_files:212                seen_files.add(fname)213                images.append(u)214        images = images[:25]215216        return [self._row_to_listing(217            row, url=url, name=name, address=address, sector=sector,218            city=city, description=description, amenities=amenities,219            images=images)220            for row in self._suite_rows(soup)]221
Files main
Menu

Theme