SPB Git

Repository Public

bestlife.py 11.1 KB 276 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/bestlife.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/bestlife.py : connecteur Les Gestions Bestlife91#   (lesgestionsbestlife.com) — 500+ portes en gestion à Sherbrooke92#   (Fleurimont, Rock Forest, Mont-Bellevue), East Angus, Richmond.93#   WordPress Divi + WooCommerce : chaque logement est un « produit »94#   (archive /appartements-a-louer-sherbrooke/, cartes li.product avec titre95#   « adresse – type », prix WooCommerce — promo = del/ins — et taxonomie96#   product_cat-<type>). Les fiches produit (via self.detail, cache BD)97#   ajoutent la disponibilité (« Disponible dès maintenant »), les listes98#   Inclusions/Spécifications et la galerie photos. La ville est extraite de99#   la parenthèse du titre (« (East-Angus) », « (Richemond) ») — Sherbrooke100#   par défaut. external_id = slug du produit (stable).101# -----------------------------------------------------------------------------102from __future__ import annotations103104import hashlib105import re106107from bs4 import BeautifulSoup108109from ..schema import Listing, normalize_unit_type, parse_price110from .base import BaseConnector111112BASE = "https://lesgestionsbestlife.com"113LIST_URL = f"{BASE}/appartements-a-louer-sherbrooke/"114115# « (East-Angus) », « (Richemond) »… -> vraie ville ; sinon Sherbrooke116_CITY_PARENS = {117    "east-angus": "East Angus", "east angus": "East Angus",118    "richemond": "Richmond", "richmond": "Richmond",119    "windsor": "Windsor", "magog": "Magog",120}121_VARIANT_IMG = re.compile(r"[?&](?:resize|fit)=", re.I)122123124def _clean_price_label(label: str) -> str:125    """« 1,150 $ » (virgule de milliers WooCommerce) -> compatible parse_price."""126    return re.sub(r"(\d),(\d{3})", r"\1\2", label)127128129class BestlifeConnector(BaseConnector):130    source_id = "bestlife"131    request_delay = 0.6132    max_details = 30      # garde-fou fiches produit (vraies requêtes)133134    def fetch(self) -> list[Listing]:135        html = self.get(LIST_URL).text136        soup = BeautifulSoup(html, "html.parser")137138        listings: dict[str, Listing] = {}139        for card in soup.select("li.product"):140            try:141                lst = self._parse_card(card)142            except Exception:143                continue144            if lst and lst.external_id not in listings:145                listings[lst.external_id] = lst146147        # fiches produit (cache BD) : dispo, inclusions, spécifications, photos148        self._fetched = 0149        for lst in listings.values():150            key = hashlib.sha1(151                f"{lst.title}|{lst.price_label}".encode("utf-8")).hexdigest()152            try:153                payload = self.detail(lst.external_id, key,154                                      lambda u=lst.url: self._fetch_detail(u))155            except Exception:156                continue157            self._apply_detail(lst, payload)158        return list(listings.values())159160    # -- carte produit ---------------------------------------------------------------161    def _parse_card(self, card) -> Listing | None:162        link = card.select_one("a.woocommerce-loop-product__link[href]")163        title_el = card.select_one("h2")164        if not (link and title_el):165            return None166        url = link["href"]167        m = re.search(r"/produit/([^/]+)/?", url)168        if not m:169            return None170        slug = m.group(1)171        title = re.sub(r"\s+", " ", title_el.get_text(" ", strip=True)).strip()172173        # « 1082 Sainte-Thérèse – 4 1/2 » -> adresse + type174        addr_part = re.split(r"\s*[–—-]\s*(?=\d\s*1/2|Loft|Studio|Chambre)",175                             title, maxsplit=1, flags=re.I)[0].strip()176        unit_type = normalize_unit_type(title)177        if not re.fullmatch(r"\d½\+?|6½\+|Studio|Loft|Chambre|Maison",178                            unit_type or ""):179            unit_type = ""180181        # ville depuis la parenthèse du titre (sinon Sherbrooke)182        city = "Sherbrooke"183        pm = re.search(r"\(([^)]+)\)", title)184        if pm:185            key = pm.group(1).strip().lower()186            if key in _CITY_PARENS:187                city = _CITY_PARENS[key]188                addr_part = re.sub(r"\s*\([^)]+\)", "", addr_part).strip()189190        # prix WooCommerce : promo = <del>régulier</del> <ins>courant</ins>191        price = None192        price_label = ""193        price_el = card.select_one("span.price")194        if price_el:195            price_label = re.sub(r"\s+", " ",196                                 price_el.get_text(" ", strip=True)).strip()197            ins = price_el.select_one("ins .woocommerce-Price-amount")198            amount = ins or price_el.select_one(".woocommerce-Price-amount")199            if amount:200                price = parse_price(_clean_price_label(201                    amount.get_text(" ", strip=True)))202203        img = card.select_one("img[src]")204        images = []205        if img:206            src = (img.get("data-orig-file") or img["src"]).strip()207            if src.startswith("http"):208                images.append(src)209210        return Listing(211            source=self.source_id,212            external_id=slug,213            url=url,214            title=title,215            address=addr_part,216            sector="",             # non publié sur la carte217            city=city,218            unit_type=unit_type,219            price=price,220            price_label=price_label,221            availability="",       # complété par la fiche produit222            images=images,223        )224225    # -- fiche produit ------------------------------------------------------------226    def _fetch_detail(self, url: str) -> dict:227        if self._fetched >= self.max_details:228            raise RuntimeError("budget de fiches détail atteint")229        self._fetched += 1230        html = self.get(url).text231        soup = BeautifulSoup(html, "html.parser")232        out: dict = {}233234        # « Disponible dès maintenant » / « Disponible le 1er septembre » —235        # ligne en emphase de la fiche (jamais les messages techniques du thème)236        for el in soup.find_all(["em", "strong", "p", "h3"]):237            t = re.sub(r"\s+", " ", el.get_text(" ", strip=True)).strip()238            if re.match(r"^Disponible\b", t) and len(t) <= 80:239                out["availability"] = t240                break241242        # listes Inclusions / Spécifications (commodités affichées)243        amenities: list[str] = []244        for h in soup.find_all(["h3", "h4"]):245            t = h.get_text(" ", strip=True)246            if t in ("Inclusions", "Spécifications"):247                ul = h.find_next("ul")248                if ul:249                    for li in ul.select("li"):250                        item = re.sub(r"\s+", " ", li.get_text(" ", strip=True))251                        if item and item not in amenities:252                            amenities.append(item)253        out["amenities"] = amenities[:25]254255        # galerie photos (pleine taille i0.wp.com sans resize)256        images: list[str] = []257        for img in soup.select(".woocommerce-product-gallery img[src], "258                               ".et_pb_gallery img[src]"):259            src = (img.get("data-orig-file") or img.get("src") or "").strip()260            src = src.split("?")[0] if _VARIANT_IMG.search(src) else src261            if src.startswith("http") and src not in images:262                images.append(src)263        out["images"] = images[:20]264        return out265266    def _apply_detail(self, lst: Listing, d: dict) -> None:267        if not d:268            return269        if d.get("availability"):270            lst.availability = d["availability"]271        if d.get("amenities"):272            lst.amenities = list(dict.fromkeys(lst.amenities + d["amenities"]))273        if d.get("images"):274            merged = list(dict.fromkeys(d["images"] + lst.images))275            lst.images = merged[:20]276
Files main
Menu

Theme