SPB Git

Repository Public

elk.py 11.0 KB 281 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/elk.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-0913# Last Modified    : 2026-08-0914#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/elk.py : connecteur ELK Property Management (elkproperty.com)91#   Gestionnaire du Plateau/Hull à Gatineau. Très vieux site PHP (PinchCMS),92#   HTTP SEULEMENT (pas de HTTPS) : la page residential_new.php?typeID=193#   (Ottawa/Gatineau) rend côté serveur un bloc par complexe :94#     - div.results-in : adresse (h2 + code postal), galerie lightbox,95#       description à puces (secteur « Hull District »), contact, note de96#       loyer « Starting from $1050.00/month | Hydro/Gas not included »,97#       listes « Building Amenities » / « Apartment Features » ;98#     - div.record-bttm#units_<id> : colonnes parallèles BEDROOMS / FLOORPLAN99#       (PDF) / RENT alignées par index -> une annonce par TYPOLOGIE affichée100#       sous « NOW RENTING / AVAILABLE APARTMENTS ».101#   Les complexes hors Québec (Halifax sous typeID=2, adresses ON) sont102#   exclus : seules les adresses « QC » passent.103# -----------------------------------------------------------------------------104from __future__ import annotations105106import re107108from bs4 import BeautifulSoup109110from ..schema import Listing, normalize_unit_type111from .base import BaseConnector112113BASE = "http://www.elkproperty.com"114LIST_URL = f"{BASE}/residential_new.php?typeID=1"115116_SECTORS = ["Hull", "Aylmer", "Buckingham", "Plateau"]117118119class ElkConnector(BaseConnector):120    source_id = "elk"121    request_delay = 1.0122    max_images = 12123124    def fetch(self) -> list[Listing]:125        soup = BeautifulSoup(self.get(LIST_URL).text, "html.parser")126127        # tables d'unités par complexe : record-bttm id="units_<id>"128        units_by_id: dict[str, list[dict]] = {}129        for block in soup.select("div.record-bttm[id^='units_']"):130            pid = block["id"].split("_", 1)[1]131            cols: dict[str, list] = {}132            for ul in block.find_all("ul"):133                h2 = ul.find("h2")134                if not h2:135                    continue136                head = h2.get_text(" ", strip=True).upper()137                cells = ul.find_all("li")[1:]     # après l'en-tête138                cols[head] = cells139            rows: list[dict] = []140            beds = cols.get("BEDROOMS", [])141            rents = cols.get("RENT", [])142            plans = cols.get("FLOORPLAN", [])143            for i, bcell in enumerate(beds):144                b = re.sub(r"\s+", " ", bcell.get_text(" ", strip=True))145                if not b:146                    continue147                row: dict = {"beds": b}148                if i < len(rents):149                    row["rent"] = re.sub(r"\s+", " ",150                                         rents[i].get_text(" ", strip=True))151                if i < len(plans):152                    a = plans[i].find("a", href=True)153                    if a:154                        row["plan"] = a["href"]155                rows.append(row)156            units_by_id[pid] = rows157158        listings: dict[str, Listing] = {}159        for res in soup.select("div.results-in"):160            try:161                self._parse_complex(res, units_by_id, listings)162            except Exception:163                continue164        return list(listings.values())165166    def _parse_complex(self, res, units_by_id: dict,167                       listings: dict[str, Listing]) -> None:168        right = res.select_one(".gallary-right")169        h2 = right.find("h2") if right else None170        if not h2:171            return172        span = h2.find("span")173        locality = span.get_text(" ", strip=True) if span else ""174        if span:175            span.extract()176        street = re.sub(r"\s+", " ", h2.get_text(" ", strip=True)).strip()177        # « Gatineau QC, J9A 3J2 » : Québec seulement (Halifax/Ottawa exclus)178        if not re.search(r"\bQC\b", locality):179            return180        m = re.match(r"^([A-Za-zÀ-ÿ' .-]+?)\s+QC", locality)181        city = (m.group(1).strip() if m else "Gatineau")182183        # id du complexe via la galerie lightbox « apt_6 » -> table units_6184        pid = ""185        gal = res.select_one("[data-lightbox]")186        if gal:187            mm = re.search(r"(\d+)$", gal.get("data-lightbox", ""))188            if mm:189                pid = mm.group(1)190191        images = []192        for a in res.select("a[data-lightbox][href]"):193            u = a["href"]194            if not u.startswith("http"):195                u = BASE + (u if u.startswith("/") else "/" + u)196            if u not in images:197                images.append(u)198199        text = right.get_text("\n", strip=True)200        # description à puces + note de loyer, texte fidèle de l'agence201        desc_lines = [re.sub(r"\s+", " ", l).strip() for l in text.split("\n")]202        desc_lines = [l for l in desc_lines203                      if l and not re.match(r"(?i)^(contact us today|rent:$)", l)204                      and "@" not in l and not re.match(r"^\d{3}-\d{3}-\d{4}$", l)]205        rent_note = ""206        for l in desc_lines:207            if re.search(r"(?i)starting from \$", l):208                rent_note = l209                break210211        sector = ""212        for s in _SECTORS:213            if re.search(rf"(?i)\b{s}\b", text):214                sector = s215                break216217        amenities: list[str] = []218        for h4 in right.find_all("h4"):219            sec = h4.get_text(" ", strip=True)220            if not re.search(r"(?i)amenities|features", sec):221                continue222            ul = h4.find_next("ul")223            for li in (ul.find_all("li") if ul else []):224                t = re.sub(r"\s+", " ", li.get_text(" ", strip=True))225                if t and t not in amenities:226                    amenities.append(t)227228        contact = {}229        mm = re.search(r"([\w.+-]+@elkproperty\.com)", text)230        if mm:231            contact["email"] = mm.group(1)232        mm = re.search(r"\b(\d{3})[-. ](\d{3})[-. ](\d{4})\b", text)233        if mm:234            contact["phone"] = f"{mm.group(1)}-{mm.group(2)}-{mm.group(3)}"235236        address = f"{street}, {city}"237        rows = units_by_id.get(pid, [])238        for row in rows:239            beds = row["beds"]240            mm = re.match(r"^(\d+)", beds)241            unit_type = (normalize_unit_type(f"{mm.group(1)} chambres")242                         if mm else "")243            rent = row.get("rent", "")244            price = None245            pm = re.search(r"\$\s*([\d,]+)", rent)246            if pm:247                price = float(pm.group(1).replace(",", ""))248249            details: dict = {}250            if contact:251                details["contact"] = dict(contact)252            plan = row.get("plan", "")253            if plan:254                if not plan.startswith("http"):255                    plan = BASE + (plan if plan.startswith("/")256                                   else "/" + plan)257                details["floorplan_pdf"] = plan258259            ext = f"{pid}-{mm.group(1) if mm else beds}"260            if ext in listings:261                continue262            desc = " — ".join(x for x in [263                " ".join(desc_lines[:6]), rent_note] if x)264            listings[ext] = Listing(265                source=self.source_id,266                external_id=ext,267                url=f"{LIST_URL}#units_{pid}",268                title=f"{street} — {beds} bedroom(s)",269                address=address,270                sector=sector,271                city=city,272                unit_type=unit_type,273                price=price,274                price_label=rent,275                availability="Now renting",   # bandeau de la section source276                description=desc[:900],277                amenities=amenities,278                details=details,279                images=images[: self.max_images],280            )281
Files main
Menu

Theme