SPB Git

Repository Public

contraste.py 11.9 KB 284 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/contraste.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/contraste.py : connecteur Contraste Immobilier91#   (contrasteimmobilier.ca — Beauport, Limoilou, Ste-Foy, Val-Bélair,92#    Lévis, St-Nicolas, St-Romuald). Site WordPress rendu serveur :93#   page d'accueil = cartes d'immeubles, pages immeubles = unités94#   individuelles (div.building-stack-unit avec attributs data-*).95# -----------------------------------------------------------------------------96from __future__ import annotations9798import json99import re100101from bs4 import BeautifulSoup102103from ..schema import Listing, infer_city, normalize_unit_type, parse_price104from .base import BaseConnector105106BASE = "https://contrasteimmobilier.ca"107108# Villes admissibles (agglomération Québec / Lévis) — ex. Beaupré est exclue.109ALLOWED_CITIES = {"quebec", "québec", "levis", "lévis"}110111ADDR_RE = re.compile(112    r"\d{1,5}[^,<>]{2,60},\s*[^,<>]{2,40},\s*Qu[ée]bec(?:,\s*[A-Z]\d[A-Z]\s?\d[A-Z]\d)?"113)114# Adresse courte des pages « projet » (ex. « 2784 ave Sasseville ») : un115# titre Elementor qui commence par un numéro civique + type de voie.116ADDR_SHORT_RE = re.compile(117    r"^\d{1,5}\s+(?:rue|av(?:e|enue)?\.?|boul(?:evard)?\.?|ch(?:emin)?\.?|"118    r"all[ée]e|place|c[ôo]te|montée|route)\b.{2,50}$", re.I)119PHONE_RE = re.compile(r"\(?\b([2-9]\d{2})\)?[\s.\-]?(\d{3})[\s.\-](\d{4})\b")120EMAIL_RE = re.compile(r"\b[\w.+-]+@[\w-]+\.[\w.]+\b")121122123class ContrasteConnector(BaseConnector):124    source_id = "contraste"125    request_delay = 0.6126    max_buildings = 30       # garde-fou de crawl127128    def fetch(self) -> list[Listing]:129        listings: list[Listing] = []130        try:131            home = self.get(BASE).text132        except Exception:133            return listings134135        # 1) Cartes d'immeubles sur la page d'accueil : nom + ville + lien136        soup = BeautifulSoup(home, "html.parser")137        buildings: dict[str, dict] = {}138        for a in soup.select('a[href*="/appartements/"]'):139            href = (a.get("href") or "").split("?")[0]140            m = re.search(r"/appartements/([a-z0-9\-]+)/?$", href)141            if not m:142                continue143            slug = m.group(1)144            text = re.sub(r"\s+", " ", a.get_text(" ", strip=True))145            if not text or slug in buildings:146                continue147            # "Quartier Élévation I Lévis 6 unités disponibles ... Découvrir"148            name = re.split(r"\s(?:Québec|Lévis|Beaupré)\b", text)[0].strip()149            city_m = re.search(r"\b(Québec|Lévis|Beaupré)\b", text)150            city = city_m.group(1) if city_m else ""151            buildings[slug] = {"name": name or slug, "city": city}152153        # 2) Pages d'immeubles : unités individuelles154        for i, (slug, meta) in enumerate(buildings.items()):155            if i >= self.max_buildings:156                break157            if meta["city"] and meta["city"].lower() not in ALLOWED_CITIES:158                continue  # hors Québec/Lévis (ex. Beaupré)159            url = f"{BASE}/appartements/{slug}/"160            try:161                html = self.get(url).text162            except Exception:163                continue164            bsoup = BeautifulSoup(html, "html.parser")165166            # Adresse civique de l'immeuble (bloc Elementor)167            address = sector = ""168            headings = [el.get_text(" ", strip=True)169                        for el in bsoup.select(".elementor-heading-title")]170            for h in headings:171                m = ADDR_RE.search(h)172                if m:173                    address = m.group(0).strip()174                    break175            if not address:176                m = ADDR_RE.search(html)177                if m:178                    address = m.group(0).strip()179            if not address:180                # Pages « projet » (Ellipse, Émergence II…) : adresse courte181                # sans ville dans le hero.182                for h in headings:183                    if ADDR_SHORT_RE.match(h):184                        address = h.strip()185                        break186            if address:187                parts = [p.strip() for p in address.split(",")]188                if len(parts) >= 2:189                    sector = parts[1]190            city = infer_city(sector, default=meta["city"] or "Québec")191192            # Description (meta og:description)193            desc = ""194            og = bsoup.find("meta", attrs={"property": "og:description"})195            if og and og.get("content"):196                desc = og["content"].strip()[:600]197198            # CARACTÉRISTIQUES de l'immeuble (répéteur JetEngine) :199            # inclusions, animaux, stationnement… — texte source fidèle.200            bldg_amenities = [el.get_text(" ", strip=True) for el in bsoup.select(201                ".jet-listing-dynamic-repeater__item span")]202            bldg_amenities = [a for a in dict.fromkeys(bldg_amenities) if a][:25]203204            # Contact « Pour prendre rendez-vous » (pages projet)205            contact: dict = {}206            for h in headings:207                m = EMAIL_RE.search(h)208                if m and not contact.get("email"):209                    contact["email"] = m.group(0)210                m = PHONE_RE.search(h)211                if m and not contact.get("phone"):212                    contact["phone"] = f"{m.group(1)}-{m.group(2)}-{m.group(3)}"213            details = {"contact": contact} if contact else {}214215            for unit in bsoup.select("div.building-stack-unit"):216                try:217                    pid = unit.get("data-pid") or ""218                    name = unit.get("data-name") or pid219                    rooms = unit.get("data-rooms") or ""220                    price_raw = unit.get("data-price") or ""221                    if not pid:222                        continue223                    # Images : data-images = JSON [{urlPreview, url}, ...]224                    images: list[str] = []225                    cover = unit.get("data-image") or ""226                    if cover:227                        images.append(cover)228                    try:229                        for img in json.loads(unit.get("data-images") or "[]"):230                            u = (img or {}).get("url") or ""231                            if u:232                                images.append(u)233                    except (ValueError, TypeError):234                        pass235                    images = [u for u in dict.fromkeys(images)236                              if not re.search(r"logo|icon|favicon", u, re.I)]237238                    avail_el = unit.select_one(".building-stack-available-soon")239                    availability = (avail_el.get_text(" ", strip=True)240                                    if avail_el else "Disponible")241                    # data-price="0" = prix non affiché sur la carte242                    if price_raw in ("", "0"):243                        price_raw = ""244                    price_label = f"{price_raw}$/mois" if price_raw else ""245246                    # data-size est toujours « 0 » chez Contraste (non rempli) ;247                    # on ne le prend que s'il devient plausible un jour.248                    area = None249                    try:250                        size = float(unit.get("data-size") or 0)251                        if 80 <= size <= 20000:252                            area = size253                    except (TypeError, ValueError):254                        pass255256                    # Type de bâtiment (ex. « Maison de ville ») exposé en data-*257                    amenities = list(bldg_amenities)258                    housing = (unit.get("data-housing-type") or "").strip()259                    if housing:260                        amenities.append(housing)261262                    listings.append(Listing(263                        source=self.source_id,264                        external_id=f"{slug}-{pid}",265                        url=url,266                        title=f"{meta['name']} — unité {name}",267                        address=address,268                        sector=sector,269                        city=city,270                        unit_type=normalize_unit_type(rooms),271                        price=parse_price(price_label),272                        price_label=price_label,273                        availability=availability,274                        area_sqft=area,275                        description=desc,276                        amenities=amenities,277                        details=dict(details),278                        images=images,279                    ))280                except Exception:281                    continue282283        return listings284
Files main
Menu

Theme