SPB Git

Repository Public

forsa.py 9.9 KB 252 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/forsa.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/forsa.py : connecteur Gestion immobilière Forsa (gestionforsa.com)91#   Squarespace. La page /logements-disponibles expose toutes les unités en92#   sections « liste » (li.list-item) : titre « 2 1/2, Joliette - MAINTENANT »93#   (type + ville + dispo), description (adresse civique + prix mensuel) et94#   bouton « Détails » vers une page par unité (slug stable = external_id).95#   Fiches détail (cache BD) : description riche + galerie complète.96#   NB : robots.txt interdit /api/ et ?format=json → HTML seulement.97# -----------------------------------------------------------------------------98from __future__ import annotations99100import hashlib101import re102103from bs4 import BeautifulSoup104105from ..schema import Listing, normalize_unit_type, parse_price106from .base import BaseConnector107108BASE = "https://www.gestionforsa.com"109LIST_URL = f"{BASE}/logements-disponibles"110111# villes réelles du parc (titres des cartes) — abréviations usuelles → nom complet112_CITY_MAP = {113    "joliette": "Joliette",114    "st-gabriel": "Saint-Gabriel",115    "saint-gabriel": "Saint-Gabriel",116    "st-charles-borromee": "Saint-Charles-Borromée",117    "saint-charles-borromee": "Saint-Charles-Borromée",118    "montreal": "Montréal",119}120121_FORMAT_QS = re.compile(r"\?format=\d+w$")122123124def _city_from(raw: str) -> str:125    key = (raw.strip().lower()126           .replace("é", "e").replace("è", "e").replace("ô", "o"))127    return _CITY_MAP.get(key, raw.strip())128129130class ForsaConnector(BaseConnector):131    source_id = "forsa"132    request_delay = 0.8133    max_pages = 1        # tout tient sur la page /logements-disponibles134    max_details = 20     # garde-fou fiches détail (vraies requêtes)135136    def fetch(self) -> list[Listing]:137        html = self.get(LIST_URL).text138        soup = BeautifulSoup(html, "html.parser")139        listings: dict[str, Listing] = {}140        for item in soup.select("li.list-item"):141            try:142                self._parse_card(item, listings)143            except Exception:144                continue145146        # fiches détail (cache BD) : description complète + galerie147        self._fetched = 0148        for lst in listings.values():149            card_key = hashlib.sha1(150                f"{lst.title}|{lst.price_label}|{lst.availability}"151                .encode("utf-8")).hexdigest()152            try:153                payload = self.detail(lst.external_id, card_key,154                                      lambda u=lst.url: self._fetch_detail(u))155            except Exception:156                continue157            if payload.get("description"):158                lst.description = payload["description"]159            if payload.get("images"):160                lst.images = payload["images"]161        return list(listings.values())162163    # -- carte « liste » Squarespace -------------------------------------------164    def _parse_card(self, item, listings: dict[str, Listing]) -> None:165        title_el = item.select_one(".list-item-content__title")166        btn = item.select_one("a.list-item-content__button[href]")167        if not (title_el and btn):168            return169        title = title_el.get_text(" ", strip=True)170        slug = btn["href"].strip("/").split("/")[-1]171        if not slug or slug in listings:172            return173174        # exclusions : chalet à la journée (location saisonnière, pas un bail),175        # locaux commerciaux, stationnements, rangements176        if re.search(r"chalet|commercial|stationnement|rangement|entrep[oô]t",177                     title, re.I):178            return179180        # titre « 2 1/2, Joliette - MAINTENANT » → type, ville, disponibilité181        unit_type, city, availability = "", "", ""182        parts = [p.strip() for p in title.split(",", 1)]183        unit_type = normalize_unit_type(parts[0])184        rest = parts[1] if len(parts) > 1 else ""185        m = re.split(r"\s[-–]\s|,", rest, maxsplit=1)186        if m:187            city = _city_from(m[0])188            if len(m) > 1:189                availability = m[1].strip()190191        # description de la carte : adresse civique (1er §) + prix (§ avec $)192        address, price_label = "", ""193        desc_el = item.select_one(".list-item-content__description")194        if desc_el:195            paras = [p.get_text(" ", strip=True)196                     for p in desc_el.select("p") if p.get_text(strip=True)]197            for p in paras:198                if not price_label and "$" in p:199                    price_label = p200                elif not address:201                    address = p202203        img = item.select_one("img.list-image[data-src]")204        images = [_FORMAT_QS.sub("", img["data-src"])] if img else []205206        # « 1 290 $ par mois » : espace fine de milliers → retirer pour parse_price207        clean_price = re.sub(r"(\d)[\s  ](\d{3})", r"\1\2", price_label)208209        listings[slug] = Listing(210            source=self.source_id,211            external_id=slug,212            url=f"{BASE}/{slug}",213            title=title,214            address=address,215            city=city,216            unit_type=unit_type,217            price=parse_price(clean_price),218            price_label=price_label,219            availability=availability,220            images=images,221        )222223    # -- fiche détail -------------------------------------------------------------224    def _fetch_detail(self, url: str) -> dict:225        """Description riche (environnement/logement/immeuble, inclusions,226        exclusions) et galerie complète de la page unité."""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        # bloc texte principal = le plus long des blocs HTML (hors pied de page)235        best = ""236        for b in soup.select("div.sqs-block-html"):237            t = b.get_text("\n", strip=True)238            if re.search(r"Squarespace|©|Information de contact", t):239                continue240            if len(t) > len(best):241                best = t242        if best:243            out["description"] = re.sub(r"[ \t]+", " ", best).strip()[:1500]244245        images: list[str] = []246        for img in soup.select("img[data-src*='squarespace-cdn']"):247            u = _FORMAT_QS.sub("", img["data-src"]).strip()248            if u.startswith("http") and u not in images:249                images.append(u)250        out["images"] = images[:30]251        return out252
Files main
Menu

Theme