SPB Git

Repository Public

info_logement.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/info_logement.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/info_logement.py : connecteur Info-Logement (info-logement.com)91#   Gestionnaire locatif de Lanaudière (Joliette, St-Charles-Borromée,92#   Notre-Dame-des-Prairies, Berthierville…). Site custom : la liste93#   /logements/tous (paginée ?page=N, filtre gardé en session) expose des94#   cartes <a class="result"> avec data-logid stable, adresse (h2), tableau95#   Dimensions/Ville/Disponibilité, loyer et badge « En rénovation ». Les96#   fiches détail (via cache BD) ajoutent description, commodités,97#   proximités, adresse complète, galerie et GPS (LatLng de la carte).98#   robots.txt : « Disallow: » vide (tout permis).99# -----------------------------------------------------------------------------100from __future__ import annotations101102import hashlib103import re104105from bs4 import BeautifulSoup106107from ..schema import Listing, normalize_unit_type, parse_price108from .base import BaseConnector109110BASE = "https://www.info-logement.com"111LIST_URL = f"{BASE}/logements/tous"112PAGE_URL = f"{BASE}/logements?page={{n}}"113114_LATLNG_RE = re.compile(r"LatLng\((-?\d+\.\d+),\s*(-?\d+\.\d+)\)")115_THUMB_SUFFIX = re.compile(r"-\d{2,4}x\d{2,4}(?=\.(?:jpg|jpeg|png|webp)$)", re.I)116117118class InfoLogementConnector(BaseConnector):119    source_id = "info_logement"120    request_delay = 0.7121    max_pages = 10      # garde-fou de pagination (3 pages actuellement)122    max_details = 60    # garde-fou fiches détail (vraies requêtes)123124    def fetch(self) -> list[Listing]:125        listings: dict[str, Listing] = {}126        for page in range(1, self.max_pages + 1):127            # /logements/tous fixe le filtre « tous » en session ; les pages128            # suivantes se parcourent via /logements?page=N (mêmes cookies)129            url = LIST_URL if page == 1 else PAGE_URL.format(n=page)130            try:131                html = self.get(url).text132            except Exception:133                break134            soup = BeautifulSoup(html, "html.parser")135            cards = soup.select("a.result")136            if not cards:137                break138            before = len(listings)139            for card in cards:140                try:141                    self._parse_card(card, listings)142                except Exception:143                    continue144            if len(listings) == before:      # page sans nouvelle annonce145                break146147        # fiches détail (cache BD) : description, commodités, GPS, galerie148        self._fetched = 0149        for lst in listings.values():150            card_key = hashlib.sha1(151                f"{lst.title}|{lst.price_label}|{lst.availability}|{lst.url}"152                .encode("utf-8")).hexdigest()153            try:154                payload = self.detail(lst.external_id, card_key,155                                      lambda u=lst.url: self._fetch_detail(u))156            except Exception:157                continue158            self._apply_detail(lst, payload)159160        return list(listings.values())161162    # -- carte de la liste --------------------------------------------------------163    def _parse_card(self, card, listings: dict[str, Listing]) -> None:164        url = card.get("href", "")165        # type dans l'URL : /logements/<ville>/<type>/<dim>/<id> —166        # on exclut garages/commercial (le site liste aussi des garages)167        m = re.search(r"/logements/([^/]+)/([^/]+)/([^/]+)/(\d+)$", url)168        if not m:169            return170        type_slug, ext_id = m.group(2), m.group(4)171        if re.search(r"garage|commercial|stationnement|rangement", type_slug):172            return173        if ext_id in listings:174            return175176        h2 = card.select_one("h2")177        address = h2.get_text(" ", strip=True) if h2 else ""178        rows: dict[str, str] = {}179        for tr in card.select("table.resultData tr"):180            tds = tr.find_all("td")181            if len(tds) == 2:182                rows[tds[0].get_text(strip=True).lower()] = \183                    tds[1].get_text(" ", strip=True)184        city = rows.get("ville", "")185        dim = rows.get("dimensions", "")186        availability = rows.get("disponibilité", "")187        price_el = card.select_one("p.left")188        price_label = price_el.get_text(" ", strip=True) if price_el else ""189190        # badge « En rénovation » : conservé (texte source) dans la description191        reno = card.select_one("span.reno")192        reno_txt = reno.get_text(" ", strip=True) if reno else ""193194        images: list[str] = []195        img = card.select_one(".resultPic img[src]")196        if img and img["src"].startswith("http"):197            images.append(_THUMB_SUFFIX.sub("", img["src"]))198199        listings[ext_id] = Listing(200            source=self.source_id,201            external_id=ext_id,          # data-logid / id numérique de l'URL202            url=url,203            title=address,204            address=address,205            sector="",206            city=city,                   # ville affichée sur la carte207            unit_type=normalize_unit_type(dim),208            price=parse_price(price_label),209            price_label=price_label,210            availability=availability,211            description=reno_txt,212            images=images,213        )214215    # -- fiche détail ------------------------------------------------------------216    def _fetch_detail(self, url: str) -> dict:217        """Description, commodités/proximités, adresse complète, GPS, galerie."""218        if self._fetched >= self.max_details:219            raise RuntimeError("budget de fiches détail atteint")220        self._fetched += 1221        html = self.get(url).text222        soup = BeautifulSoup(html, "html.parser")223        out: dict = {}224225        # sections titrées h1 : Commodités / À proximité de / Description226        for h in soup.find_all("h1"):227            name = h.get_text(strip=True)228            if name not in ("Commodités", "À proximité de", "Description"):229                continue230            lines: list[str] = []231            sib = h.find_next_sibling()232            while sib is not None and sib.name != "h1":233                for t in sib.stripped_strings:234                    t = re.sub(r"\s+", " ", t).strip()235                    if t and t not in lines:236                        lines.append(t)237                sib = sib.find_next_sibling()238            if name == "Description":239                out["description"] = "\n".join(lines)[:1200]240            else:241                out.setdefault("amenities", []).extend(lines[:15])242243        # adresse complète (« 1400, Line-Rainville, app. 201, Joliette QC J6E »)244        h1 = soup.find("h1")245        if h1:246            nxt = h1.find_next(string=re.compile(r"QC"))247            if nxt:248                out["address"] = re.sub(r"\s+", " ", str(nxt)).strip()249250        m = _LATLNG_RE.search(html)251        if m:252            out["lat"], out["lng"] = float(m.group(1)), float(m.group(2))253254        images: list[str] = []255        for img in soup.select('img[src*="/medias/"]'):256            src = _THUMB_SUFFIX.sub("", img["src"])257            if src.startswith("http") and src not in images:258                images.append(src)259        if images:260            out["images"] = images[:25]261        return out262263    def _apply_detail(self, lst: Listing, d: dict) -> None:264        if not d:265            return266        if d.get("description"):267            lst.description = (lst.description + "\n" + d["description"]).strip()268        if d.get("amenities"):269            lst.amenities = list(dict.fromkeys(d["amenities"]))270        if d.get("address"):271            lst.address = d["address"]272        if d.get("images"):273            lst.images = d["images"]274        if d.get("lat") is not None and d.get("lng") is not None:275            lst.lat, lst.lng = d["lat"], d["lng"]276
Files main
Menu

Theme