SPB Git

Repository Public

oklouer.py 12.4 KB 298 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/oklouer.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/oklouer.py : connecteur OK Louer (oklouer.com)91#   Appartements meublés en location temporaire à Québec (Haute-Ville,92#   Centre-Ville, Limoilou, Charlesbourg/Beauport). Pages rendues serveur.93#   Les pages de secteurs exposent des cartes `div.unit` structurées :94#   data-lat/data-lng, adresse (h3), icônes lits/chambres/salles de bain,95#   animaux permis (ico-paws). La fiche ajoute le prix, la galerie et la96#   climatisation (ico-clim). Le secteur Lac-Beauport est exclu.97# -----------------------------------------------------------------------------98from __future__ import annotations99100import re101102from bs4 import BeautifulSoup103104from ..schema import Listing, infer_city, normalize_unit_type, parse_price105from .base import BaseConnector106107BASE = "https://www.oklouer.com"108109# secteurs conservés (lac-beauport exclu : hors Québec/Lévis)110SECTORS = {111    "haute-ville": "Haute-Ville (Montcalm, St-Jean-Baptiste)",112    "centre-ville": "Centre-Ville (St-Roch)",113    "limoilou": "Limoilou",114    "charlesbourg-beauport": "Charlesbourg / Beauport",115}116117# une fiche d'unité se termine par un code postal, ex.118# /2-1-2-limoilou-1905a-de-la-bastille-quebec-qc-g1l-4b9119DETAIL_RE = re.compile(r"-qc-g\d[a-z]-?\d[a-z]\d$", re.I)120121# icônes des cartes/fiches -> libellé de commodité (le compte vient du span)122_ICON_LABELS = {123    "ico-bed": ("lit", "lits"),124    "ico-bedroom": ("chambre", "chambres"),125    "ico-bathroom": ("salle de bain", "salles de bain"),126}127128129def _parse_icon_list(ul) -> tuple[str, list[str]]:130    """Extrait (type d'unité brut, commodités) d'un `ul.icon-list`.131132    Icônes à compteur (lits, chambres, salles de bain) -> "2 lits" ;133    icônes booléennes (ico-paws, ico-clim) -> texte du tooltip `title`134    (ex. "Animaux permis", "Avec air climatisé sur demande").135    """136    unit_raw = ""137    amenities: list[str] = []138    for li in ul.find_all("li"):139        classes = li.get("class") or []140        if "nb-pieces" in classes:141            unit_raw = re.sub(r"\s+", " ", li.get_text(" ", strip=True))142            continue143        ico = li.find("i")144        if not ico:145            continue146        ico_cls = " ".join(ico.get("class") or [])147        count_el = li.select_one("span.count")148        count = count_el.get_text(strip=True) if count_el else ""149        for key, (sing, plur) in _ICON_LABELS.items():150            if key in ico_cls and count.isdigit():151                n = int(count)152                amenities.append(f"{n} {plur if n > 1 else sing}")153                break154        else:155            if "ico-paws" in ico_cls or "ico-clim" in ico_cls:156                title = (ico.get("title") or "").strip()157                if title:158                    amenities.append(title)159    return unit_raw, amenities160161162class OkLouerConnector(BaseConnector):163    source_id = "oklouer"164    request_delay = 0.6165    max_details = 80         # garde-fou166167    def fetch(self) -> list[Listing]:168        # 1) Cartes structurées des pages de secteurs : lien, adresse,169        #    lat/lng, type d'unité, lits/chambres/salles de bain, animaux170        cards: dict[str, dict] = {}   # path -> infos de carte171        for slug, sector in SECTORS.items():172            try:173                html = self.get(f"{BASE}/logements/{slug}").text174            except Exception:175                continue176            soup = BeautifulSoup(html, "html.parser")177            for unit in soup.select("div.logements div.unit"):178                a = unit.find("a", href=True)179                path = a["href"] if a else ""180                if not DETAIL_RE.search(path) or path in cards:181                    continue182                info: dict = {"sector": sector}183                try:184                    info["lat"] = float(unit.get("data-lat"))185                    info["lng"] = float(unit.get("data-lng"))186                except (TypeError, ValueError):187                    pass188                h3 = unit.select_one("div.unit-infos h3")189                if h3:190                    info["address"] = re.sub(r"\s+", " ",191                                             h3.get_text(" ", strip=True))192                ul = unit.select_one("ul.icon-list")193                if ul:194                    info["unit_raw"], info["amenities"] = _parse_icon_list(ul)195                cards[path] = info196197        # 2) Fiche détaillée de chaque unité : prix, galerie, adresse propre,198        #    climatisation (l'icône ico-clim n'apparaît que sur la fiche)199        listings: list[Listing] = []200        for i, (path, card) in enumerate(sorted(cards.items())):201            if i >= self.max_details:202                break203            try:204                html = self.get(BASE + path).text205            except Exception:206                continue207            try:208                soup = BeautifulSoup(html, "html.parser")209210                # Adresse : entête de fiche, sinon carte de la page secteur211                address = card.get("address", "")212                h3 = soup.select_one("h3.unit-address")213                if h3:214                    address = re.sub(r"\s+", " ", h3.get_text(" ", strip=True))215216                # Secteur plus précis si présent dans le slug de la fiche217                sector = card.get("sector", "")218                for key, name in (("centre-ville", SECTORS["centre-ville"]),219                                  ("haute-ville", SECTORS["haute-ville"]),220                                  ("limoilou", SECTORS["limoilou"]),221                                  ("charlesbourg", SECTORS["charlesbourg-beauport"])):222                    if key in path:223                        sector = name224                        break225226                # Prix mensuel : "* À partir de 75$/jour ou 1100$/mois"227                price = None228                price_label = ""229                price_el = soup.select_one("div.price")230                price_text = (re.sub(r"\s+", " ", price_el.get_text(" ", strip=True))231                              if price_el else soup.get_text(" ", strip=True))232                pm = re.search(r"([\d\s  ]{2,})\$\s*/\s*mois", price_text)233                if pm:234                    price = parse_price(pm.group(1).strip() + "$")235                lm = re.search(r"À partir de[^(\n]*", price_text)236                if lm:237                    price_label = re.sub(r"\s+", " ", lm.group(0)).strip(" *")238                    if "mois" not in price_label and pm:239                        price_label += f" ou {pm.group(1).strip()}$/mois"240241                # Icônes de la fiche (lits, chambres, sdb, animaux, clim) ;242                # repli sur les icônes de la carte liste243                amenities = list(card.get("amenities") or [])244                unit_raw = card.get("unit_raw", "")245                ul = soup.select_one("ul.icon-list")246                if ul:247                    u_raw, amen = _parse_icon_list(ul)248                    unit_raw = u_raw or unit_raw249                    for a_txt in amen:250                        if a_txt not in amenities:251                            amenities.append(a_txt)252                if "Meublé" not in amenities:253                    amenities.append("Meublé")254255                # Type d'unité : icônes, sinon slug256                unit_type = normalize_unit_type(unit_raw)257                tm = re.match(r"^/(\d)-1-2-", path)258                if not unit_type:259                    if tm:260                        unit_type = normalize_unit_type(f"{tm.group(1)} 1/2")261                    elif path.startswith("/studios-lofts"):262                        unit_type = "Loft"263                    elif path.startswith("/studio"):264                        unit_type = "Studio"265                    elif path.startswith("/condo"):266                        unit_type = "Condo"267268                # Images (galerie /uploads/m/)269                imgs = re.findall(r'(?:src|href)="(/uploads/m/[^"]+'270                                  r'\.(?:jpg|jpeg|png|webp))"', html, re.I)271                images = [BASE + u for u in dict.fromkeys(imgs)][:25]272273                title = address or path.strip("/").replace("-", " ").title()274                listings.append(Listing(275                    source=self.source_id,276                    external_id=path.strip("/"),277                    url=BASE + path,278                    title=f"{unit_type + ' — ' if unit_type else ''}{title}"279                          " (meublé, location temporaire)",280                    address=address,281                    sector=sector,282                    city=infer_city(sector, default="Québec"),283                    unit_type=unit_type,284                    price=price,285                    price_label=price_label,286                    availability="",287                    description="Appartement meublé en location temporaire "288                                "(court, moyen ou long terme).",289                    amenities=amenities,290                    images=images,291                    lat=card.get("lat"),292                    lng=card.get("lng"),293                ))294            except Exception:295                continue296297        return listings298
Files main
Menu

Theme