Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/westdale.py10# Module : louka11# Repository : https://git.spboucher.ai/lou-ka12# Created : 2026-08-2713# Last Modified : 2026-08-2714#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 (Québec + expansion Ontario)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# connectors/westdale.py : connecteur Westdale Properties (westdaleproperties.com)91# Gestionnaire familial de Toronto/North York (14 immeubles résidentiels au92# moment de l'écriture : Forest Hill, Redpath, St George, Don Mills…).93# Site legacy ASP.NET « VICommunity » entièrement rendu serveur, AUCUN94# anti-bot (requests direct suffit ; réponses gzip gérées par requests) :95# - la PAGE D'ACCUEIL est la liste : blocs `.bld-content` avec96# onclick="window.open('rental/<slug>','_self')", nom (h3), résumé97# (p.brief), « N suite options | From $X » (p.options) et vignette ;98# - la fiche /rental/<slug> donne l'adresse civique + téléphone (premier99# <p><a maps>), la description (#txtDetail), la galerie (#mainslider),100# les commodités (h2 Suite/Building amenities + Utilities -> tags), le101# stationnement, et l'accordéon Options : une ligne `.btn_option` par102# type de suite — nom, « N (lit) N (bain) » (icônes svg, baths peut103# être 1.5), « Starting at $X », « Size: N ft² » — avec plan d'étage104# et photos de la suite (#single_phoN, « Not Available. » = pas de105# photos, PAS une indisponibilité).106# Une annonce PAR TYPE DE SUITE (ligne d'accordéon avec prix), repli « une107# annonce par immeuble » avec le prix « From $X » du bloc de la liste.108# Les prix sont des « Starting at » de catalogue (« Please call for109# availabilities ») : availability laissée vide — rien d'inventé. Idem110# animaux : la section « Pet-Friendly » est vide partout -> pets None.111# Fiches revisitées via self.detail() seulement quand le bloc de la liste112# change (résumé, nombre d'options, prix plancher, vignette).113# Expansion Ontario — gaté LOUKA_ONTARIO=1 : sans la variable, disabled.114# -----------------------------------------------------------------------------115from __future__ import annotations116117import hashlib118import os119import re120121from bs4 import BeautifulSoup122123from ..schema import Listing, normalize_unit_type124from .base import BaseConnector125126BASE = "https://www.westdaleproperties.com"127128# Gate expansion Ontario : hors registre tant que LOUKA_ONTARIO=1 absent129_ONTARIO = os.environ.get("LOUKA_ONTARIO") == "1"130131_SLUG_RE = re.compile(r"window\.open\('rental/([^']+)'")132_PRICE_RE = re.compile(r"(?:From|Starting at)\s*\$\s*([\d,]+(?:\.\d{2})?)",133 re.I)134_SQFT_RE = re.compile(r"Size:\s*([\d,]+)\s*ft", re.I)135# colonnes lits/bains : « 1 <img class='bed-svg'…> 1.5 <img class='bath-svg'…> »136_BED_RE = re.compile(r"([\d.]+)\s*<img[^>]*bed-svg")137_BATH_RE = re.compile(r"([\d.]+)\s*<img[^>]*bath-svg")138139140class WestdaleConnector(BaseConnector):141 source_id = "westdale"142 request_delay = 1.0143 disabled = not _ONTARIO # gate expansion Ontario (LOUKA_ONTARIO=1)144 max_properties = 25 # garde-fou (14 immeubles au 2026-08)145 max_listings = 150 # garde-fou lignes de suites (~66 au 2026-08)146 max_images = 15147148 # -- liste : blocs .bld-content de la page d'accueil --------------------------149 def fetch(self) -> list[Listing]:150 soup = BeautifulSoup(self.get(BASE + "/").text, "html.parser")151 listings: list[Listing] = []152 count = 0153 for block in soup.select(".bld-content[onclick]"):154 m = _SLUG_RE.search(block.get("onclick") or "")155 if not m:156 continue # blocs non résidentiels (tel:, Admin/…)157 if count >= self.max_properties or \158 len(listings) >= self.max_listings:159 break160 count += 1161 try:162 listings.extend(self._listings(m.group(1), block))163 except Exception:164 continue165 return listings[: self.max_listings]166167 # -- annonces d'un immeuble (une par type de suite) ---------------------------168 def _listings(self, slug: str, block) -> list[Listing]:169 # nom : le h3 du bloc texte (PAS le h3.bonus du bandeau promo)170 h3 = block.select_one(".text h3") or block.h3171 name = h3.get_text(" ", strip=True) if h3 else slug172 block_txt = block.get_text(" ", strip=True)173 img = block.find("img")174 thumb = self._abs((img.get("src") or "").strip()) if img else ""175176 url = f"{BASE}/rental/{slug}"177 # fiche revisitée seulement quand le bloc de la liste change178 feed_key = hashlib.sha1(179 f"{block_txt}|{thumb}".encode("utf-8")).hexdigest()180 d = self.detail(slug, feed_key, lambda: self._fetch_detail(url))181182 city = (d.get("city") or "").strip() or "Toronto"183 details: dict = {}184 if d.get("phone"):185 details["contact"] = {"phone": d["phone"]}186 if d.get("parking"):187 details["Stationnement"] = d["parking"]188189 base_images = [u for u in (d.get("images") or []) if u] or \190 ([thumb] if thumb else [])191192 common = dict(193 source=self.source_id, url=url,194 address=d.get("address") or "", city=city, province="ON",195 description=(d.get("description") or "")[:900],196 amenities=(d.get("amenities") or [])[:25],197 )198199 out: list[Listing] = []200 for su in d.get("suites") or []:201 if su.get("price") is None:202 continue # ligne sans « Starting at » : rien d'inventé203 images = [u for u in (su.get("images") or []) + base_images204 if u][: self.max_images]205 beds = su.get("beds")206 out.append(Listing(207 external_id=f"{slug}-{su['id']}",208 title=f"{name} — {su['name']}" if su.get("name") else name,209 unit_type=self._unit_type(su.get("name") or "", beds),210 bedrooms=beds,211 bathrooms=su.get("baths"),212 price=su["price"],213 price_label=f"À partir de {su['price']:.0f} $ /mois",214 area_sqft=su.get("sqft"),215 details=dict(details),216 images=images,217 **common,218 ))219 if out:220 return out221222 # repli : une annonce par immeuble avec le « From $X » du bloc liste223 mp = _PRICE_RE.search(block_txt)224 if not mp:225 return [] # ni suite avec prix ni prix plancher : rien226 price = float(mp.group(1).replace(",", ""))227 return [Listing(228 external_id=slug,229 title=name,230 price=price,231 price_label=f"À partir de {price:.0f} $ /mois",232 details=details,233 images=base_images[: self.max_images],234 **common,235 )]236237 @staticmethod238 def _unit_type(su_name: str, beds: float | None) -> str:239 """Type d'unité : nom de la ligne (Bachelor -> Studio) sinon les cc."""240 ut = normalize_unit_type(su_name)241 if ut and ut != su_name.strip():242 return ut243 if beds == 0:244 return "Studio"245 if beds is not None:246 return normalize_unit_type(f"{int(beds)} chambres")247 return ut248249 @staticmethod250 def _abs(u: str) -> str:251 return u if u.startswith("http") else (BASE + u if u else "")252253 # -- fiche /rental/<slug> ------------------------------------------------------254 def _fetch_detail(self, url: str) -> dict:255 soup = BeautifulSoup(self.get(url).text, "html.parser")256 out: dict = {"suites": []}257258 # adresse + téléphone : premier <p> sous le h1 (liens maps + tel:)259 h1 = soup.find("h1", class_="property_title")260 p = h1.find_next("p") if h1 else None261 if p:262 a_map = p.find("a", href=re.compile(r"google\.com/maps"))263 if a_map:264 addr = a_map.get_text(" ", strip=True)265 out["address"] = addr266 # « 484 Avenue Rd, Toronto, ON » -> ville avant « ON »267 parts = [x.strip() for x in addr.split(",")]268 if len(parts) >= 2 and parts[-1].upper().startswith("ON"):269 out["city"] = parts[-2]270 a_tel = p.find("a", href=re.compile(r"^tel:"))271 if a_tel:272 out["phone"] = a_tel.get_text(" ", strip=True)273274 desc = soup.find(id="txtDetail")275 if desc:276 out["description"] = desc.get_text(" ", strip=True)277278 # galerie de l'immeuble (#mainslider)279 images: list[str] = []280 slider = soup.find(id="mainslider")281 for a in (slider.find_all("a", class_="pics") if slider else []):282 u = self._abs((a.get("href") or "").strip())283 if u and u not in images:284 images.append(u)285 out["images"] = images[: self.max_images]286287 # commodités (suite + immeuble) et services inclus288 amenities: list[str] = []289 for div in soup.select(".amenity_tags, .utility_tags"):290 t = div.get_text(" ", strip=True)291 if t and len(t) < 90 and t not in amenities:292 amenities.append(t)293 out["amenities"] = amenities294295 # stationnement : <p> sous le h2 « Parking »296 for h2 in soup.find_all("h2"):297 if h2.get_text(strip=True).lower() == "parking":298 pp = h2.find_next("p")299 if pp:300 out["parking"] = pp.get_text(" ", strip=True)[:300]301 break302303 # accordéon Options : une ligne .btn_option par type de suite304 for row in soup.select("#accordion .group .btn_option"):305 rid = (row.get("id") or "").strip()306 cols = row.select("[class*=col-sm]")307 su_name = cols[0].get_text(" ", strip=True) if cols else ""308 if not rid or not su_name:309 continue310 row_html = str(row)311 mb = _BED_RE.search(row_html)312 mba = _BATH_RE.search(row_html)313 txt = row.get_text(" ", strip=True)314 mp = _PRICE_RE.search(txt)315 msq = _SQFT_RE.search(txt)316 sqft = float(msq.group(1).replace(",", "")) if msq else None317 # photos propres à la suite (« Not Available. » = aucune)318 su_imgs: list[str] = []319 pho = soup.find(id=f"single_pho{rid}")320 for a in (pho.find_all("a") if pho else []):321 u = self._abs((a.get("href") or "").strip())322 if u and u not in su_imgs:323 su_imgs.append(u)324 beds = float(mb.group(1)) if mb else \325 (0.0 if re.search(r"bachelor|studio", su_name, re.I) else None)326 out["suites"].append({327 "id": rid,328 "name": su_name,329 "beds": beds,330 "baths": float(mba.group(1)) if mba else None,331 "sqft": sqft if sqft and 80 <= sqft <= 20000 else None,332 "price": (float(mp.group(1).replace(",", ""))333 if mp else None),334 "images": su_imgs[:5],335 })336 return out337