Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/werkliv.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/werkliv.py : connecteur Werkliv (logement étudiant)91# werkliv.com est le site corporatif ; la location de ses immeubles passe92# par sa plateforme University Apartments (universityapartments.ca —93# WordPress + FacetWP rendu serveur). Immeubles montréalais : Palay94# (2025 rue Peel, centre-ville) et Le Mojave (3476 rue Saint-Dominique,95# Plateau/Milton-Parc). Une annonce par typologie (1-BEDROOM, 4-BEDROOM...),96# loyer par personne (colocation étudiante meublée).97# -----------------------------------------------------------------------------98from __future__ import annotations99100import hashlib101import re102103from bs4 import BeautifulSoup104105from ..schema import Listing106from .base import BaseConnector107108BASE = "https://universityapartments.ca"109LIST_URL = f"{BASE}/apartment-listings/?_listings_city_en=montreal"110111# Immeuble (nom affiché) -> (slug fiche immeuble, secteur)112BUILDINGS = {113 "palay": ("palay", "Centre-ville (Ville-Marie)"),114 "le mojave": ("le-mojave", "Milton-Parc / Plateau-Mont-Royal"),115 "mojave": ("le-mojave", "Milton-Parc / Plateau-Mont-Royal"),116}117118ADDR_RE = re.compile(119 r"\d{2,5}[^<>\"|]{2,60}?(?:Montr[ée]al)[,\s]+QC(?:\s+[A-Z]\d[A-Z]\s?\d[A-Z]\d)?")120121# Émojis/puces en tête des items de commodités des fiches122_EMOJI_PREFIX_RE = re.compile(r"^[\W_]+", re.UNICODE)123124125def _unit_type(label: str) -> str:126 """'1-BEDROOM' -> 3½, '4-BEDROOM' -> 6½, 'STUDIO' -> Studio."""127 s = (label or "").lower()128 if "studio" in s:129 return "Studio"130 m = re.search(r"(\d+)", s)131 if m:132 n = int(m.group(1))133 return "Studio" if n == 0 else f"{n + 2}½"134 return label.strip()135136137class WerklivConnector(BaseConnector):138 source_id = "werkliv"139 request_delay = 0.6140 max_details = 20 # garde-fou141142 def fetch(self) -> list[Listing]:143 listings: list[Listing] = []144 try:145 html = self.get(LIST_URL).text146 except Exception:147 return listings148 soup = BeautifulSoup(html, "html.parser")149150 addresses: dict[str, str] = {} # slug immeuble -> adresse151 seen: set[str] = set()152 for card in soup.select(".lcl-card"):153 try:154 a = card.select_one('a.lcl-link[href*="/listings/"]') or \155 card.select_one('a[href*="/listings/"]')156 if not a:157 continue158 url = (a.get("href") or "").split("?")[0]159 m = re.search(r"/listings/([^/]+)/?$", url)160 if not m or m.group(1) in seen:161 continue162 slug = m.group(1)163 seen.add(slug)164165 city_el = card.select_one(".lcl-city")166 city_raw = city_el.get_text(" ", strip=True) if city_el else ""167 if "montreal" not in city_raw.lower():168 continue # hors Montréal (Halifax, PEI...)169170 typo_el = card.select_one(".lcl-title .h4, .lcl-title")171 typology = typo_el.get_text(" ", strip=True) if typo_el else ""172 prop_el = card.select_one(".lcl-property")173 building = prop_el.get_text(" ", strip=True) if prop_el else ""174 price_el = card.select_one(".lcl-price")175 price_label = price_el.get_text(" ", strip=True) \176 if price_el else ""177 price = None178 pm = re.search(r"\$\s*([\d,]+)", price_label)179 if pm:180 try:181 v = float(pm.group(1).replace(",", ""))182 price = v if 100 <= v <= 20000 else None183 except ValueError:184 pass185186 avail = ""187 av_el = card.select_one(".lcl-available span")188 if av_el:189 avail = re.sub(r"\s+", " ",190 av_el.get_text(" ", strip=True))191 amenities = ["Logement étudiant"]192 for chip in card.select(".lcl-chip"):193 amenities.append(re.sub(r"\s+", " ",194 chip.get_text(" ", strip=True)))195196 bslug, sector = BUILDINGS.get(building.strip().lower(),197 ("", ""))198 # adresse depuis la fiche de l'immeuble (mise en cache)199 address = ""200 if bslug:201 if bslug not in addresses:202 addresses[bslug] = self._building_address(bslug)203 address = addresses[bslug]204205 images = []206 header = card.select_one("[data-bg]")207 if header and header.get("data-bg", "").startswith("http"):208 images.append(header["data-bg"])209210 listings.append(Listing(211 source=self.source_id,212 external_id=slug,213 url=url,214 title=f"{building} — {typology} (par chambre)",215 address=address,216 sector=sector,217 city="Montréal",218 unit_type=_unit_type(typology),219 price=price,220 price_label=f"{price_label} (par personne)"221 if price_label else "",222 availability=avail,223 amenities=list(dict.fromkeys(amenities)),224 images=images,225 ))226 except Exception:227 continue228229 # Fiches détaillées (photos, description, dispo ACF, bail, commodités)230 # via le cache BD : 1 vraie requête par annonce et par changement.231 self._detail_requests = 0232 for i, lst in enumerate(listings):233 if i >= self.max_details:234 break235 key = hashlib.sha1(236 f"{lst.title}|{lst.price_label}|{lst.availability}"237 f"|{'|'.join(lst.amenities)}".encode("utf-8")).hexdigest()238239 def _fetch(url=lst.url) -> dict:240 if self._detail_requests >= self.max_details:241 return {}242 self._detail_requests += 1243 return self._fetch_detail(url)244245 try:246 payload = self.detail(lst.external_id, key, _fetch) or {}247 except Exception:248 payload = {}249 self._apply_detail(lst, payload)250 return listings251252 # -- fiche immeuble (adresse) --------------------------------------------------253 def _building_address(self, slug: str) -> str:254 try:255 html = self.get(f"{BASE}/properties/{slug}/").text256 except Exception:257 return ""258 m = ADDR_RE.search(html.replace("+", " "))259 if not m:260 return ""261 addr = re.sub(r"\s+", " ", m.group(0)).strip()262 return addr.replace("Montreal", "Montréal")263264 # -- fiche annonce ---------------------------------------------------------------265 def _fetch_detail(self, url: str) -> dict:266 """Fiche d'une annonce : photos, description, sidebar ACF structuré267 (Available, Lease Terms) et commodités (BUILDING AMENITIES, cuisine).268 """269 html = self.get(url).text270 soup = BeautifulSoup(html, "html.parser")271272 imgs = re.findall(273 r'https://universityapartments\.ca/wp-content/uploads/'274 r'[^"\s\\\)]+\.(?:jpg|jpeg|png|webp)', html)275 imgs = [u for u in dict.fromkeys(imgs)276 if not re.search(r"logo|icon|favicon|chrome|-\d{2,3}x\d{2,3}\.",277 u, re.I)]278279 description = ""280 og = soup.find("meta", attrs={"property": "og:description"})281 if og and og.get("content"):282 description = og["content"].strip()[:600]283 else:284 p = soup.select_one(".fl-rich-text p, article p")285 if p:286 description = p.get_text(" ", strip=True)[:600]287288 # Sidebar ACF : <dl class="acf-data"><dt>Available</dt><dd>...</dd></dl>289 available = ""290 for dl in soup.select("dl.acf-data"):291 dts = [d.get_text(" ", strip=True) for d in dl.select("dt")]292 dds = [d.get_text(" ", strip=True) for d in dl.select("dd")]293 for k, v in zip(dts, dds):294 if k.lower().startswith("available") and v:295 available = v296 lease_terms = [t.get_text(" ", strip=True)297 for t in soup.select(".rental-term")]298299 # Commodités de l'immeuble : items <p> à émoji après le titre300 # « BUILDING AMENITIES » (même bloc rich-text).301 amenities: list[str] = []302 head = soup.find(string=re.compile(r"BUILDING AMENITIES", re.I))303 if head:304 h = head.find_parent(["h1", "h2", "h3", "h4", "strong"]) \305 or head.parent306 node = h.find_parent(["h1", "h2", "h3", "h4"]) or h307 for sib in node.find_next_siblings():308 if sib.name in ("h1", "h2", "h3"):309 break310 text = _EMOJI_PREFIX_RE.sub("", sib.get_text(" ", strip=True))311 text = re.sub(r"\s+", " ", text).strip()312 if not text or text.startswith("***") or "Disclaimer" in text:313 break314 if len(text) > 90:315 continue316 # « Wi-Fi ($) » = payant : ne pas laisser la normalisation317 # le classer « internet inclus » (lacune générique notée)318 if text.endswith("($)"):319 continue320 # stationnement à vélo ≠ stationnement auto321 if re.search(r"\bbike (?:parking|storage)\b", text, re.I):322 text = "Espace vélos (sous-sol)"323 if text not in amenities:324 amenities.append(text)325326 # Électroménagers de la cuisine partagée (ligne explicite de la fiche)327 kitchen = soup.find(string=re.compile(328 r"appliances,? including a fridge", re.I))329 if kitchen:330 amenities.append(_EMOJI_PREFIX_RE.sub(331 "", re.sub(r"\s+", " ", str(kitchen)).strip()))332333 return {"images": imgs, "description": description,334 "available": available, "lease_terms": lease_terms,335 "amenities": amenities}336337 def _apply_detail(self, lst: Listing, payload: dict) -> None:338 if not payload:339 return340 if payload.get("images"):341 lst.images = list(dict.fromkeys(342 lst.images + payload["images"]))[:40]343 if payload.get("description"):344 lst.description = payload["description"]345 if not lst.availability and payload.get("available"):346 lst.availability = f"Available {payload['available']}"347 if payload.get("lease_terms"):348 lst.amenities.append(349 "Lease terms: " + ", ".join(payload["lease_terms"]))350 for a in payload.get("amenities") or []:351 if a not in lst.amenities:352 lst.amenities.append(a)353