SPB Git

Repository Public

obohec.py 9.3 KB 237 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/obohec.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/obohec.py : connecteur O'bohec (obohec.ca) — Voyer & Tremblay91#   Trois immeubles locatifs sur le boulevard Michèle-Bohec, Blainville92#   (27 unités affichées : studio, 1 et 2 chambres). WordPress (thème maison93#   « trema ») rendu serveur : /projets-locatifs/obohec/ liste des cartes94#   .item-listing-unite groupées par en-tête .item-unites-filter95#   (data-immeuble-id → Immeuble 1/2/3, classe filter-<id> sur la carte).96#   Carte : .title-unite (Studio/1 chambre/2 chambres), .number-unite97#   (« #105 Tout meublé Disponible septembre 2026 »), .disponiblite-unite98#   (Loué/Disponible), caractéristiques .car-* (chambres, bain, balcon,99#   stationnement, orientation, superficie) et plan image + PDF. AUCUN prix100#   publié (« Prix sur demande »). On exclut « BUREAU DE LOCATION » et les101#   unités louées. Granularité : unité. ⚠️ Le volet VENTE du site est ignoré.102# -----------------------------------------------------------------------------103from __future__ import annotations104105import re106107from bs4 import BeautifulSoup108109from ..schema import Listing, normalize_unit_type110111from .base import BaseConnector112113BASE = "https://obohec.ca"114LIST_URL = f"{BASE}/projets-locatifs/obohec/"115116ADDRESS = "Boulevard Michèle-Bohec, Blainville"117CITY = "Blainville"118119FILTER_RE = re.compile(r"^filter-(\d+)$")120AREA_RE = re.compile(r"(\d[\d\s  ]*)\s*pi", re.I)121AVAIL_RE = re.compile(r"Disponible[^#<]*", re.I)122123124class ObohecConnector(BaseConnector):125    source_id = "obohec"126    request_delay = 0.6127    max_images = 10128129    @staticmethod130    def _txt(node, sel: str) -> str:131        el = node.select_one(sel)132        return re.sub(r"\s+", " ", el.get_text(" ", strip=True)) if el else ""133134    def fetch(self) -> list[Listing]:135        html = self.get(LIST_URL).text136        soup = BeautifulSoup(html, "html.parser")137138        # data-immeuble-id -> « Immeuble N »139        buildings: dict[str, str] = {}140        for h in soup.select(".item-unites-filter[data-immeuble-id]"):141            buildings[str(h["data-immeuble-id"])] = re.sub(142                r"\s+", " ", h.get_text(" ", strip=True))143144        listings: list[Listing] = []145        seen: set[str] = set()146        for it in soup.select(".item-listing-unite"):147            title_u = self._txt(it, ".title-unite")148            if re.search(r"bureau\s+de\s+location", title_u, re.I):149                continue                              # local commercial150            dispo = self._txt(it, ".disponiblite-unite")151            if re.search(r"lou[ée]", dispo, re.I):152                continue153154            num_raw = self._txt(it, ".number-unite")155            m = re.search(r"#\s*([\w-]+)", num_raw)156            if m is None:157                continue158            num = m.group(1)159160            bid = ""161            for cls in it.get("class", []):162                fm = FILTER_RE.match(cls)163                if fm:164                    bid = fm.group(1)165                    break166            ext_id = f"imm{bid}-{num}" if bid else num167            if ext_id in seen:168                continue169            seen.add(ext_id)170            building = buildings.get(bid, "")171172            m = AVAIL_RE.search(num_raw)173            availability = m.group(0).strip() if m else (dispo or "Disponible")174            furnished = bool(re.search(r"meubl[ée]", num_raw, re.I))175176            beds = None177            v = self._txt(it, ".car-chambres span")178            if v.isdigit():179                beds = float(v)180            baths = None181            v = self._txt(it, ".car-bain span")182            if v.replace(".", "", 1).isdigit():183                baths = float(v)184185            area = None186            m = AREA_RE.search(self._txt(it, ".car-superficie span"))187            if m:188                try:189                    v2 = float(re.sub(r"[\s  ]", "", m.group(1)))190                    if 100 <= v2 <= 10000:191                        area = v2192                except ValueError:193                    pass194195            amenities = [a for a in (196                "Tout meublé" if furnished else "",197                f"Balcon/terrasse : {self._txt(it, '.car-balcon-terrasse span')}"198                if self._txt(it, ".car-balcon-terrasse span") else "",199                f"Stationnement {self._txt(it, '.car-stationnement span')}"200                if self._txt(it, ".car-stationnement span") else "",201                f"Orientation {self._txt(it, '.car-orientation span')}"202                if self._txt(it, ".car-orientation span") else "",203            ) if a]204205            images: list[str] = []206            img = it.select_one(".image-plan-unite img[src]")207            if img is not None and str(img["src"]).startswith("http"):208                images.append(str(img["src"]))209            details: dict = {}210            pdf = it.select_one('a.btn-imprimable[href], a[href$=".pdf"]')211            if pdf is not None:212                details["floor_plan"] = pdf["href"]213214            desc_bits = [f"Unité #{num}", building, title_u,215                         "Tout meublé" if furnished else ""]216            listings.append(Listing(217                source=self.source_id,218                external_id=ext_id,219                url=LIST_URL,220                title=f"O'bohec — {building or 'Blainville'} — Unité #{num}"221                      f" ({title_u})",222                address=ADDRESS,223                city=CITY,224                unit_type=normalize_unit_type(title_u),225                bedrooms=beds,226                bathrooms=baths,227                price=None,228                price_label="Prix sur demande",229                availability=availability,230                area_sqft=area,231                description=" — ".join(b for b in desc_bits if b),232                amenities=amenities,233                details=details,234                images=images,235            ))236        return listings237
Files main
Menu

Theme