SPB Git

Repository Public

oxford.py 9.9 KB 245 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/oxford.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/oxford.py : connecteur Appartements Oxford (appartoxford.com)91#   Complexe locatif de Lennoxville (Sherbrooke), près de l'Université92#   Bishop's. WordPress + Elementor : une fiche par TYPE d'unité (2½ tout93#   inclus, 3½, 4½, 5½), listées dans le menu « Logements » de la page94#   d'accueil. Chaque fiche affiche le prix (« À partir de 760$ / par mois »)95#   et, seulement quand des unités sont libres, un encart de disponibilité96#   (« 1 unité disponible 1er octobre 2026 », widget Elementor à visibilité97#   conditionnelle) : les fiches SANS cet encart ne sont pas des annonces98#   courantes et sont écartées. Caractéristiques (listes à pictos), description99#   et galerie extraites de la fiche. Peu de requêtes (accueil + ~4 fiches) :100#   pas de cache détail nécessaire — la disponibilité doit être relue à chaque101#   synchronisation.102# -----------------------------------------------------------------------------103from __future__ import annotations104105import re106107from urllib.parse import unquote108109from bs4 import BeautifulSoup110111from ..schema import Listing, normalize_unit_type112from .base import BaseConnector113114BASE = "https://appartoxford.com"115116# variantes redimensionnées WordPress -> pleine taille117_SIZE_SUFFIX = re.compile(r"-\d{2,4}x\d{2,4}(?=\.(?:jpg|jpeg|png|webp)$)", re.I)118119# « 1 unité disponible 1er octobre 2026 » / « 2 unités disponibles maintenant »120_AVAIL_RE = re.compile(r"(\d+|une?)\s+unit[ée]s?\s+disponibles?\b", re.I)121_NO_AVAIL_RE = re.compile(r"aucune\s+unit[ée]", re.I)122123# bruit d'en-tête dans les listes à pictos (coordonnées du site)124_HEADER_NOISE_RE = re.compile(r"\+?1?\s?8\d{2}[-\s]\d{3}|Lennoxville,\s*Sherbrooke",125                              re.I)126127_MAX_FICHES = 12    # garde-fou (le menu compte ~4 fiches)128129130def _clean_unit_type(raw: str) -> str:131    ut = normalize_unit_type(raw or "")132    if re.fullmatch(r"\d½\+?|6½\+|Studio|Loft|Chambre|Maison", ut or ""):133        return ut134    return ""135136137class OxfordConnector(BaseConnector):138    source_id = "oxford"139    request_delay = 0.7140141    def fetch(self) -> list[Listing]:142        home = self.get(BASE + "/").text143        soup = BeautifulSoup(home, "html.parser")144145        # fiches du menu « Logements » : liens /appartement/<slug>/146        urls: list[str] = []147        for a in soup.select('a[href*="/appartement/"]'):148            url = (a.get("href") or "").split("#")[0]149            if not url.startswith("http"):150                url = BASE + url151            if url.rstrip("/") not in [u.rstrip("/") for u in urls]:152                urls.append(url)153154        listings: dict[str, Listing] = {}155        for url in urls[:_MAX_FICHES]:156            try:157                lst = self._parse_fiche(url)158            except Exception:159                continue160            if lst and lst.external_id not in listings:161                listings[lst.external_id] = lst162        return list(listings.values())163164    # -- fiche type d'unité -------------------------------------------------------165    def _parse_fiche(self, url: str) -> Listing | None:166        resp = self.get(url)167        url = resp.url or url          # les anciens slugs redirigent (301)168        m = re.search(r"/appartement/([^/?#]+)", url)169        if not m:170            return None171        # slug décodé + minuscule : « tres-grand-4½-a-louer » (dédoublonne172        # les variantes d'encodage %C2%BD / %c2%bd)173        ext_id = unquote(m.group(1)).lower()174175        html = resp.text176        soup = BeautifulSoup(html, "html.parser")177        text = soup.get_text(" ", strip=True)178179        # encart de disponibilité : widget texte Elementor à visibilité180        # conditionnelle, présent seulement si des unités sont libres181        availability = ""182        for w in soup.select(".elementor-widget-text-editor"):183            t = re.sub(r"\s+", " ", w.get_text(" ", strip=True)).strip()184            if _AVAIL_RE.match(t) and len(t) < 90:185                availability = t186                break187        if not availability or _NO_AVAIL_RE.search(availability):188            return None                 # pas d'unité libre = pas d'annonce189190        h1 = soup.select_one("h1")191        title = re.sub(r"\s+", " ", h1.get_text(" ", strip=True)).strip() \192            if h1 else ext_id193194        # prix : « À partir de | 1000$ / par mois » (widgets bannière)195        price_label = ""196        m_price = re.search(197            r"À partir de\s*(\d[\d\s,]*\$\s*(?:/\s*par mois|/\s*mois)?)", text)198        if m_price:199            price_label = "À partir de " + re.sub(200                r"\s+", " ", m_price.group(1)).strip()201202        # caractéristiques : listes à pictos Elementor (sans les coordonnées203        # affichées dans l'en-tête du site)204        amenities: list[str] = []205        for li in soup.select(".elementor-icon-list-text"):206            t = re.sub(r"\s+", " ", li.get_text(" ", strip=True)).strip()207            if (t and len(t) < 90 and t not in amenities208                    and not _HEADER_NOISE_RE.search(t)):209                amenities.append(t)210211        # description : contenu de l'article (widget theme-post-content de la212        # section Caractéristiques)213        description = ""214        for w in soup.select(".elementor-widget-theme-post-content, "215                             ".elementor-widget-text-editor"):216            t = re.sub(r"\s+", " ", w.get_text(" ", strip=True)).strip()217            if len(t) > 150 and not _AVAIL_RE.match(t):218                description = t[:1500]219                break220221        # galerie : photos des téléversements (logos/pictos exclus)222        images: list[str] = []223        for u in re.findall(224                r"https://appartoxford\.com/wp-content/uploads/[^\"'()\s]+"225                r"\.(?:jpg|jpeg|webp)", html, re.I):226            u = _SIZE_SUFFIX.sub("", u)227            if u not in images and not re.search(r"logo|icon", u, re.I):228                images.append(u)229230        return Listing(231            source=self.source_id,232            external_id=ext_id,233            url=url,234            title=title,235            address="",236            sector="Lennoxville",       # affiché en en-tête du site237            city="Sherbrooke",238            unit_type=_clean_unit_type(title),239            price_label=price_label,240            availability=availability,241            description=description,242            amenities=amenities[:25],243            images=images[:30],244        )245
Files main
Menu

Theme