SPB Git

Repository Public

rentalys.py 15.8 KB 380 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/rentalys.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-0613# Last Modified    : 2026-08-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/rentalys.py : connecteur Rentalys (location.rentalys.ca)91#   Agence de location du Grand Montréal (Verdun, Villeray, Rosemont,92#   Saint-Michel, Longueuil...). Site WordPress (thème Houzez) rendu93#   serveur : archives /property/page/N/ = cartes complètes (prix, adresse,94#   étiquettes de disponibilité), pages /property/<slug>/ = photos, détails,95#   description bilingue, superficie structurée (.h-area) et coordonnées96#   lat/lng (variable JS houzez_single_property_map). Les fiches passent par97#   self.detail(...) (cache BD) : re-téléchargées seulement si la carte change.98# -----------------------------------------------------------------------------99from __future__ import annotations100101import hashlib102import json103import re104105from bs4 import BeautifulSoup106107from ..schema import Listing, normalize_unit_type, parse_price, strip_accents108from .base import BaseConnector109110BASE = "https://location.rentalys.ca"111112# Arrondissements/quartiers de l'île de Montréal (partie avant ", QC" de113# l'adresse Houzez) -> ville Montréal. Les autres villes du Grand Montréal114# (Longueuil, Laval, Brossard...) restent des villes à part entière.115MTL_BOROUGHS = {116    "montreal", "verdun", "villeray", "rosemont", "la petite-patrie",117    "petite-patrie", "rosemont/la petite patrie", "saint-michel", "st-michel",118    "ville-marie", "le plateau-mont-royal", "plateau-mont-royal", "plateau",119    "hochelaga-maisonneuve", "mercier", "ahuntsic", "ahuntsic-cartierville",120    "cote-des-neiges", "notre-dame-de-grace", "ndg", "outremont", "lachine",121    "lasalle", "saint-laurent", "st-laurent", "anjou", "saint-leonard",122    "st-leonard", "montreal-nord", "riviere-des-prairies", "pointe-aux-trembles",123    "griffintown", "le sud-ouest", "sud-ouest", "pointe-saint-charles",124    "saint-henri", "st-henri", "viau", "westmount", "mont-royal",125}126127GRAND_MTL_CITIES = {128    "longueuil", "laval", "brossard", "saint-lambert", "boucherville",129    "candiac", "chateauguay", "repentigny", "terrebonne", "dorval",130    "pointe-claire", "dollard-des-ormeaux", "kirkland", "beaconsfield",131    "sainte-julie", "varennes", "chambly", "la prairie", "saint-constant",132    "sainte-catherine", "delson", "blainville", "mirabel", "saint-eustache",133    "deux-montagnes", "rosemere", "boisbriand", "sainte-therese",134    "vaudreuil-dorion", "charlemagne", "mascouche", "l'assomption",135}136137138def _city_sector(address: str, title: str) -> tuple[str, str]:139    """Déduit (ville, secteur) de l'adresse Houzez '..., Secteur, QC, Canada'."""140    sector = ""141    parts = [p.strip() for p in (address or "").split(",")]142    # partie juste avant "QC"143    for i, p in enumerate(parts):144        if p.upper().startswith("QC") and i > 0:145            sector = parts[i - 1]146            break147    if not sector and len(parts) >= 2:148        sector = parts[1]149    key = strip_accents(sector.lower())150    if key in GRAND_MTL_CITIES:151        return sector, ""                      # ville de banlieue, pas de secteur152    if key in MTL_BOROUGHS or key.replace("st-", "saint-") in MTL_BOROUGHS:153        return "Montréal", "" if key == "montreal" else sector154    # repli : préfixe du titre ("VERDUN – ...", "LONGUEUIL maison ...")155    t = strip_accents((title or "").lower())156    for c in GRAND_MTL_CITIES:157        if t.startswith(c):158            return sector or c.title(), ""159    return "Montréal", sector160161162def _unit_type(title: str, beds: str) -> str:163    t = normalize_unit_type(title)164    if re.match(r"^\d½$", t) or t in ("Studio", "Loft", "Maison", "Chambre"):165        return t166    m = re.search(r"(\d)\s*(?:1/2|½|%c2%bd)", (title or "").lower())167    if m:168        return f"{m.group(1)}½"169    if "maison" in (title or "").lower():170        return "Maison"171    if "studio" in (title or "").lower():172        return "Studio"173    try:174        n = int(str(beds).strip())175        return "Studio" if n == 0 else f"{n + 2}½"176    except (TypeError, ValueError):177        return ""178179180def _parse_houzez_price(label: str) -> float | None:181    """'$2,177/mois' -> 2177.0 (format nord-américain, $ devant)."""182    m = re.search(r"\$\s*([\d][\d,\.\s]*)", label or "")183    if not m:184        return parse_price(label)185    try:186        val = float(m.group(1).replace(",", "").replace(" ", ""))187    except ValueError:188        return None189    return val if 100 <= val <= 20000 else None190191192class _BudgetReached(Exception):193    """Plafond de requêtes « fiche » atteint pour cette synchronisation."""194195196class RentalysConnector(BaseConnector):197    source_id = "rentalys"198    request_delay = 0.6199    max_pages = 10           # garde-fou d'archives200    max_details = 60         # plafond de vraies requêtes fiche par sync201202    def fetch(self) -> list[Listing]:203        listings: dict[str, Listing] = {}204205        for page in range(1, self.max_pages + 1):206            url = f"{BASE}/property/" if page == 1 \207                else f"{BASE}/property/page/{page}/"208            try:209                html = self.get(url).text210            except Exception:211                break212            found = self._parse_archive(html, listings)213            if not found:214                break215216        # Fiches détaillées (cache BD) : photos, description, lat/lng, pi²217        self._fetches = 0218        for lst in listings.values():219            key = hashlib.sha1(220                f"{lst.title}|{lst.price_label}|{lst.availability}|"221                f"{'|'.join(lst.amenities)}".encode("utf-8")).hexdigest()222            try:223                payload = self.detail(224                    lst.external_id, key,225                    lambda u=lst.url: self._fetch_detail(u))226            except Exception:      # _BudgetReached inclus : rien de caché227                continue228            self._apply_detail(lst, payload)229230        return list(listings.values())231232    # -- archive ------------------------------------------------------------------233    def _parse_archive(self, html: str, listings: dict[str, Listing]) -> int:234        soup = BeautifulSoup(html, "html.parser")235        found = 0236        for card in soup.select(".item-listing-wrap"):237            try:238                a = card.select_one('a[href*="/property/"]')239                if not a:240                    continue241                href = (a.get("href") or "").split("?")[0]242                m = re.search(r"/property/([^/]+)/?$", href)243                if not m:244                    continue245                slug = m.group(1)246                found += 1247                if slug in listings:248                    continue249250                title_el = card.select_one(".item-title")251                title = title_el.get_text(" ", strip=True) if title_el else slug252                # exclure stationnements / commercial253                if re.search(r"parking|stationnement|commercial|garage",254                             title, re.I):255                    continue256257                addr_el = card.select_one(".item-address")258                address = addr_el.get_text(" ", strip=True) if addr_el else ""259                price_el = card.select_one(".item-price")260                price_label = price_el.get_text(" ", strip=True) \261                    if price_el else ""262263                labels = [el.get_text(" ", strip=True)264                          for el in card.select(".hz-label, .label-status,"265                                                " .labels-wrap a")]266                labels = [l for l in dict.fromkeys(labels) if l]267                availability = next(268                    (l for l in labels if re.search(r"disponible", l, re.I)), "")269                amenities = [l for l in labels270                             if not re.search(r"disponible", l, re.I)]271272                beds = baths = area = ""273                for amen in card.select(".item-amenities li"):274                    txt = amen.get_text(" ", strip=True)275                    if re.search(r"Lits?|Bed", txt, re.I):276                        beds = re.sub(r"\D", "", txt)277                    elif re.search(r"Bains?|Bath", txt, re.I):278                        baths = re.sub(r"\D", "", txt)279                    elif re.search(r"\d{3,}", txt):280                        area = re.search(r"(\d[\d,\s]*)", txt).group(1)281                if baths:282                    amenities.append(f"{baths} salle(s) de bain")283                if area:284                    amenities.append(f"{area.strip()} pi²")285286                city, sector = _city_sector(address, title)287                # repli secteur : préfixe du titre ("SAINT-MICHEL – ...")288                if not sector and city == "Montréal":289                    mt = re.match(r"^([A-ZÉÈÀÂÎÔÛÇ/\-\s\.]{3,30})[–\-—]",290                                  title)291                    if mt:292                        sector = mt.group(1).strip().title()293                img = card.select_one("img")294                cover = (img.get("src") or img.get("data-src") or "") \295                    if img else ""296297                listings[slug] = Listing(298                    source=self.source_id,299                    external_id=slug,300                    url=href,301                    title=title,302                    address=address.replace(", Canada", ""),303                    sector=sector,304                    city=city,305                    unit_type=_unit_type(title, beds),306                    price=_parse_houzez_price(price_label),307                    price_label=price_label,308                    availability=availability,309                    amenities=amenities,310                    images=[cover] if cover.startswith("http") else [],311                )312            except Exception:313                continue314        return found315316    # -- fiche --------------------------------------------------------------------317    def _fetch_detail(self, url: str) -> dict:318        """Télécharge une fiche /property/<slug>/ (appelé seulement hors cache)."""319        if self._fetches >= self.max_details:320            raise _BudgetReached()321        self._fetches += 1322        html = self.get(url).text323        payload: dict = {}324325        imgs = re.findall(326            r'https://location\.rentalys\.ca/wp-content/uploads/'327            r'[^"\s\\\)]+\.(?:jpg|jpeg|png|webp)', html)328        imgs = [u for u in dict.fromkeys(imgs)329                if not re.search(r"logo|icon|favicon|avatar|-\d{2,3}x\d{2,3}\.",330                                 u, re.I)]331        if imgs:332            payload["images"] = imgs[:40]333334        soup = BeautifulSoup(html, "html.parser")335        desc = soup.select_one("#property-description-wrap .block-content-wrap")336        if desc:337            payload["description"] = desc.get_text(" ", strip=True)[:900]338        else:339            og = soup.find("meta", attrs={"property": "og:description"})340            if og and og.get("content"):341                payload["description"] = og["content"].strip()[:900]342343        # Superficie structurée (bloc « Caractéristiques clés », libellé .h-area)344        area_ul = soup.select_one(".property-overview-data .h-area")345        if area_ul:346            strong = area_ul.find_parent("ul")347            strong = strong.find("strong") if strong else None348            if strong:349                m = re.search(r"([\d\s,]+)", strong.get_text(strip=True))350                if m:351                    try:352                        v = float(m.group(1).replace(",", "").replace(" ", ""))353                        if 80 <= v <= 20000:354                            payload["area_sqft"] = v355                    except ValueError:356                        pass357358        # Coordonnées lat/lng (variable JS de la carte Houzez)359        m = re.search(r"houzez_single_property_map\s*=\s*({.*?});", html, re.S)360        if m:361            try:362                data = json.loads(m.group(1))363                lat, lng = float(data.get("lat")), float(data.get("lng"))364                if 44 <= lat <= 63 and -80 <= lng <= -57:   # Québec plausible365                    payload["lat"], payload["lng"] = lat, lng366            except (ValueError, TypeError):367                pass368        return payload369370    @staticmethod371    def _apply_detail(lst: Listing, payload: dict) -> None:372        if payload.get("images"):373            lst.images = payload["images"]374        if payload.get("description"):375            lst.description = payload["description"]376        if payload.get("area_sqft") and lst.area_sqft is None:377            lst.area_sqft = payload["area_sqft"]378        if payload.get("lat") is not None:379            lst.lat, lst.lng = payload["lat"], payload["lng"]380
Files main
Menu

Theme