SPB Git

Repository Public

nexliving.py 12.5 KB 314 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/nexliving.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/nexliving.py : connecteur NexLiving Communities91#   (residential.nexliving.ca) — REIT pancanadien ; côté Québec : Gatineau92#   (Pointe-Gatineau, Place du Golf, Saint-James, Prado, Nelson-Morin,93#   Progrès, Futaie, Lanctot, JGR), Thurso (Fraser) et Val-d'Or94#   (Roland-Audet). Site Yardi RentCafe derrière Cloudflare (403 direct) :95#   tout passe par Scrapfly (ASP), SANS rendu JS — RentCafe embarque un bloc96#   SEO rendu serveur (#list-view-cards-hidden, li.property-box-hidden) avec97#   nom, adresse complète, lits/sdb/pi², prix « à partir de », téléphone et98#   vignette. Une annonce par propriété (uid = slug RentCafe stable).99#   Pages parcourues : /qc/gatineau/apartments, /qc/thurso/apartments,100#   /qc/val-d'or/apartments — SEULES les fiches /apartments/qc/ passent101#   (les parcs ON et NB du REIT sont exclus), avec la ville réelle par102#   annonce. La fiche propriété (galerie, description) passe par103#   self.detail() (cache BD) avec budget Scrapfly par synchronisation.104# -----------------------------------------------------------------------------105from __future__ import annotations106107import hashlib108import re109110from bs4 import BeautifulSoup111112from ..schema import Listing, parse_price113from .base import BaseConnector114115BASE = "https://residential.nexliving.ca"116# pages liste par ville québécoise (l'apostrophe de val-d'or est bien dans117# l'URL du site)118SEARCH_PATHS = ["/qc/gatineau/apartments", "/qc/thurso/apartments",119                "/qc/val-d'or/apartments"]120121# segment ville de /apartments/qc/<ville>/<slug> -> ville affichée122_QC_CITIES = {123    "gatineau": "Gatineau",124    "thurso": "Thurso",125    "val-d-or": "Val-d'Or",126}127_PROP_RE = re.compile(r"/apartments/qc/([a-z0-9\-.']+)/([a-z0-9\-]+)/")128_BED_TYPES = {"0": "Studio", "1": "3½", "2": "4½", "3": "5½", "4": "6½+"}129_PRICE_RE = re.compile(r"\$[\d,]+(?:\.\d{2})?(?:(?:\s*(?:-|to))+\s*"130                       r"\$[\d,]+(?:\.\d{2})?)?")131_IMG_RE = re.compile(132    r"https://resource\.rentcafe\.com/image/upload/[^\"'\s\\]+?"133    r"\.(?:jpg|jpeg|png|webp)", re.I)134_SKIP_IMG = re.compile(r"logo|icon|favicon|placeholder|lockup", re.I)135136137class _BudgetReached(Exception):138    """Plafond d'appels Scrapfly atteint pour cette synchronisation."""139140141class NexLivingConnector(BaseConnector):142    source_id = "nexliving"143    request_delay = 1.0144    max_images = 20145    max_details = 12         # budget de fiches propriété Scrapfly (hors cache)146147    # -- page derrière Cloudflare (bloc SEO rendu serveur, pas de JS) ----------148    def _page(self, url: str) -> str:149        html = self.get_scrapfly(url, render_js=False)150        if html and "property-box-hidden" in html:151            return html152        # seconde chance avec rendu JS complet (bloc SEO absent/incomplet)153        return self.get_scrapfly(url, rendering_wait=5000)154155    def fetch(self) -> list[Listing]:156        self._fetched = 0157        listings: list[Listing] = []158        seen: set[str] = set()159        pages_ok = 0160        for path in SEARCH_PATHS:161            try:162                html = self._page(BASE + path)163                soup = BeautifulSoup(html, "html.parser")164                cards = soup.select("#list-view-cards-hidden "165                                    "li.property-box-hidden")166                if not cards:167                    continue168                pages_ok += 1169            except Exception:170                continue171            for card in cards:172                try:173                    lst = self._card_listing(card)174                except Exception:175                    continue176                if lst and lst.external_id not in seen:177                    seen.add(lst.external_id)178                    listings.append(lst)179        if pages_ok == 0:180            # échec transitoire -> journalisé comme ÉCHEC par ingest (ok=0),181            # pas comme un passage « ok » à 0 annonce182            raise RuntimeError(183                "aucune page liste NexLiving accessible via Scrapfly")184        return listings185186    # -- une annonce par propriété -----------------------------------------------187    def _card_listing(self, card) -> Listing | None:188        a = card.select_one(".property-name a[href]")189        if not a:190            return None191        url = (a.get("href") or "").split("?")[0].replace("http://", "https://")192        m = _PROP_RE.search(url)193        if not m:194            return None          # fiche hors Québec (ON/NB) : exclue195        city = _QC_CITIES.get(m.group(1).replace("'", "-"))196        slug = m.group(2)197        addr_el = card.select_one(".card-prop-address")198        address = addr_el.get_text(" ", strip=True) if addr_el else ""199        if not city:200            # ville QC inattendue : la lire dans l'adresse (« …, Ville, QC … »)201            am = re.search(r",\s*([^,]+),\s*QC\b", address)202            if not am:203                return None      # jamais de ville inventée204            city = am.group(1).strip()205206        name = re.sub(r"\s*opens in a new tab\s*", "",207                      a.get_text(" ", strip=True)).strip()208        name = name or slug.replace("-", " ").title()209210        # lits/sdb/pi² (le type d'unité seulement si la gamme est sans211        # ambiguïté : « 3.0Beds - 3.0Beds »)212        beds = baths = sqft = ""213        for li in card.select(".card-bed-bath-rent li"):214            it = li.get_text(" ", strip=True)215            if "Bed" in it:216                beds = it217            elif "Bath" in it:218                baths = it219            elif "Sq" in it:220                sqft = re.sub(r"\s*to\s*-\s*", " - ", it)221        unit_type = ""222        bm = re.match(r"^(?:(\d)\.0Beds\s*-\s*(\d)\.0Beds|Studio\s*-\s*Studio)$",223                      beds or "")224        if bm:225            if bm.group(1) is None:226                unit_type = "Studio"227            elif bm.group(1) == bm.group(2):228                unit_type = _BED_TYPES.get(bm.group(1), "")229230        # prix « $999.00 to - $1,899.00 » ou « Call for Details »231        price = None232        price_label = ""233        pm = _PRICE_RE.search(card.get_text(" ", strip=True))234        if pm:235            price_label = re.sub(r"\s*to\s*-\s*", " - ", pm.group(0))236            price = parse_price(price_label)237            if "-" in price_label:238                price_label = "À partir de " + price_label239240        # téléphone du bureau de location (lien tel: structuré)241        phone = ""242        tel = card.select_one("a[href^='tel:']")243        if tel:244            tm = re.search(r"\(?([2-9]\d{2})\)?[\s.\-]?(\d{3})[\s.\-]?(\d{4})",245                           tel.get("href", ""))246            if tm:247                phone = f"{tm.group(1)}-{tm.group(2)}-{tm.group(3)}"248249        images: list[str] = []250        img = card.select_one("img[src*='rentcafe']")251        if img and img.get("src"):252            images.append(img["src"])253254        # fiche propriété (galerie + description) via cache BD : Scrapfly255        # n'est rappelé que si la carte liste a changé256        key = hashlib.sha1(f"{name}|{address}|{beds}|{baths}|{sqft}|"257                           f"{price_label}".encode("utf-8")).hexdigest()258        try:259            payload = self.detail(slug, key, lambda: self._fetch_detail(url))260        except Exception:261            payload = {}262        for im in (payload.get("images") or []):263            if im not in images:264                images.append(im)265266        prop_type = ""267        pt = card.select_one(".unit-types")268        if pt:269            prop_type = pt.get_text(" ", strip=True)270271        desc_parts = ([payload["description"]]272                      if payload.get("description") else [])273        desc_parts += [b for b in (prop_type, beds, baths, sqft) if b]274275        details: dict = {}276        if phone:277            details["contact"] = {"phone": phone}278279        return Listing(280            source=self.source_id,281            external_id=slug,282            url=url,283            title=name,284            address=address,285            sector="",286            city=city,287            unit_type=unit_type,288            price=price,289            price_label=price_label,290            description=" — ".join(desc_parts)[:800],291            details=details,292            images=images[: self.max_images],293        )294295    # -- fiche propriété (Scrapfly sans JS, budget par sync) ---------------------296    def _fetch_detail(self, url: str) -> dict:297        if self._fetched >= self.max_details:298            raise _BudgetReached()299        self._fetched += 1300        payload: dict = {"description": "", "images": []}301        html = self.get_scrapfly(url, render_js=False)302        if not html:303            return payload304        soup = BeautifulSoup(html, "html.parser")305        for u in dict.fromkeys(_IMG_RE.findall(html)):306            if not _SKIP_IMG.search(u) and u not in payload["images"]:307                payload["images"].append(u)308        payload["images"] = payload["images"][: self.max_images]309        paras = [p.get_text(" ", strip=True) for p in soup.find_all("p")]310        paras = [p for p in paras if len(p) > 80]311        if paras:312            payload["description"] = " ".join(paras[:2])[:600]313        return payload314
Files main
Menu

Theme