SPB Git

Repository Public

sherplex.py 9.3 KB 235 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/sherplex.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/sherplex.py : connecteur Sherplex immobilier91#   (appartementssherbrooke.com) — appartements neufs à louer en Estrie :92#   Weedon, Coaticook, Magog, Saint-François-Xavier-de-Brompton et93#   Saint-Denis-de-Brompton. Squarespace rendu serveur : pages de secteur →94#   pages de projet avec sections texte « Prix » (« 4 ½ : 1370$ à 1400$ »,95#   « Meublé à partir de : 1450$ ») et « Disponibilité ». Granularité :96#   typologie par projet (pas d'unités individuelles).97# -----------------------------------------------------------------------------98from __future__ import annotations99100import re101102from bs4 import BeautifulSoup103104from .base import BaseConnector105from ..schema import Listing, normalize_unit_type106107BASE = "https://www.appartementssherbrooke.com"108109SECTORS = [110    ("appartements-a-louer-weedon", "Weedon"),111    ("coaticook", "Coaticook"),112    ("magog", "Magog"),113    ("saint-francois-xavier-de-brompton",114     "Saint-François-Xavier-de-Brompton"),115    ("saintdenis-de-brompton", "Saint-Denis-de-Brompton"),116]117118# « 4 ½ : 1370$ à 1400$ »119TYPE_PRICE_RE = re.compile(r"^(\d)\s*(?:½|1/2)\s*[::]\s*"120                           r"(\d[\d\s  ]{2,6})\$(?:\s*à\s*"121                           r"(\d[\d\s  ]{2,6})\$)?", re.I)122# « Meublé à partir de : 1450$ » (Auberge Magog)123FURN_PRICE_RE = re.compile(r"^((?:semi-)?meublé)\s*à\s*partir\s*de\s*[::]?\s*"124                           r"(\d[\d\s  ]{2,6})\$", re.I)125TITLE_TYPES_RE = re.compile(r"(\d)\s*½")126IMG_RE = re.compile(r'https://images\.squarespace-cdn\.com/content/'127                    r'[^"\s\\)]+\.(?:jpe?g|png|webp)', re.I)128129130def _num(s: str) -> float | None:131    try:132        return float(re.sub(r"[\s  ]", "", s))133    except (TypeError, ValueError):134        return None135136137class SherplexConnector(BaseConnector):138    source_id = "sherplex"139    request_delay = 0.6140141    def fetch(self) -> list[Listing]:142        listings: list[Listing] = []143        for sector, city in SECTORS:144            try:145                html = self.get(f"{BASE}/{sector}").text146            except Exception:147                continue148            paths = sorted(set(re.findall(149                r'href="(/%s/[a-z0-9-]+)"' % re.escape(sector), html)))150            for path in paths:151                try:152                    listings += self._project(path, city)153                except Exception:154                    continue155        # dédoublonnage par external_id156        uniq: dict[str, Listing] = {}157        for l in listings:158            uniq.setdefault(l.external_id, l)159        return list(uniq.values())160161    def _project(self, path: str, city: str) -> list[Listing]:162        url = BASE + path163        html = self.get(url).text164        soup = BeautifulSoup(html, "html.parser")165        lines = [l.strip() for l in166                 soup.get_text("\n", strip=True).split("\n")]167168        name, title_txt = "", ""169        mt = re.search(r"<title>([^<]+)</title>", html)170        if mt:171            title_txt = re.sub(r"\s*(?:—|&mdash;)\s*Sherplex.*$", "",172                               mt.group(1)).strip()173            name = title_txt.split("|")[0].strip()174        slug = path.rstrip("/").rsplit("/", 1)[-1]175176        availability = ""177        for i, l in enumerate(lines):178            if l == "Disponibilité" and i + 1 < len(lines):179                availability = lines[i + 1].strip(" .")180                break181182        images = [u for u in dict.fromkeys(IMG_RE.findall(html))183                  if not re.search(r"favicon|logo|icon", u, re.I)][:15]184185        out: list[Listing] = []186187        def add(unit_type: str, type_slug: str, price: float | None,188                price_label: str, furnished: bool = False) -> None:189            out.append(Listing(190                source=self.source_id,191                external_id=f"{slug}-{type_slug}",192                url=url,193                title=f"{unit_type} — {name or city} (Sherplex)",194                city=city,195                unit_type=unit_type,196                price=price,197                price_label=price_label,198                availability=availability,199                details=({"project": name} if name else {})200                | ({"furnished": True} if furnished else {}),201                description=f"Appartements neufs Sherplex à {city}. "202                            f"{name}." if name else203                            f"Appartements neufs Sherplex à {city}.",204                images=images,205            ))206207        # 1) lignes de prix par typologie208        for l in lines:209            m = TYPE_PRICE_RE.match(l)210            if m:211                ut = normalize_unit_type(f"{m.group(1)}½")212                lo = _num(m.group(2))213                label = (f"{lo:.0f}$ à {_num(m.group(3)):.0f}$/mois"214                         if m.group(3) and _num(m.group(3))215                         else f"À partir de {lo:.0f}$/mois")216                add(ut, ut.replace("½", ".5"), lo, label)217                continue218            m = FURN_PRICE_RE.match(l)219            if m:220                # typologie tirée du <title> (« Appartements 3 ½ à louer… »)221                types = TITLE_TYPES_RE.findall(html[:2000])222                ut = normalize_unit_type(f"{types[0]}½") if types else ""223                kind = m.group(1).lower().replace("é", "e")224                price = _num(m.group(2))225                add(ut, f"{ut.replace('½', '.5') or 'x'}-{kind}", price,226                    f"{m.group(1).capitalize()} à partir de {price:.0f}$/mois",227                    furnished=("semi" not in kind))228229        # 2) aucun prix publié : une annonce par typologie du <title>230        if not out:231            for t in dict.fromkeys(TITLE_TYPES_RE.findall(title_txt)):232                ut = normalize_unit_type(f"{t}½")233                add(ut, ut.replace("½", ".5"), None, "Prix sur demande")234        return out235
Files main
Menu

Theme