SPB Git

Repository Public

quanta.py 9.0 KB 220 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/quanta.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/quanta.py : connecteur Gestion Quanta (gestionquanta.ca)91#   Firme de gestion de l'Outaouais (Gatineau, Hull, Aylmer). Vieux site92#   ASP.NET rendu serveur : la page d'accueil embarque un carrousel93#   (#CAROUSEL) avec TOUTES les fiches de location — titre (« Appartement /94#   Maison / Condo à louer »), lien Location.aspx?RentalId=<id>&rented=<0|1>,95#   secteur/ville, loyer (« 890$ par mois, non chauffé ni éclairé »),96#   description et photo. Les unités louées portent rented=1 et un overlay97#   « rented » : elles sont exclues. Les pages Location.aspx elles-mêmes98#   répondent 404 (liens morts) : l'accueil est la seule source — l'URL99#   d'annonce pointe donc sur l'accueil avec un fragment stable.100#   robots.txt : Disallow /Rentals/ (chemin des photos, jamais visité par le101#   connecteur — seule la page d'accueil, autorisée, est requêtée).102#   external_id = RentalId (H4, G1, CH2…), stable côté site.103# -----------------------------------------------------------------------------104from __future__ import annotations105106import re107from urllib.parse import parse_qs, quote, urlparse108109from bs4 import BeautifulSoup110111from ..schema import Listing, normalize_unit_type112from .base import BaseConnector113114BASE = "https://gestionquanta.ca"115HOME_URL = f"{BASE}/"116117# villes de l'Outaouais telles qu'affichées en fin de ligne secteur118_CITIES = ("hull", "gatineau", "aylmer", "buckingham", "masson")119120121class QuantaConnector(BaseConnector):122    source_id = "quanta"123    request_delay = 1.0124    max_images = 10125126    def fetch(self) -> list[Listing]:127        soup = BeautifulSoup(self.get(HOME_URL).text, "html.parser")128        carousel = soup.select_one("#CAROUSEL .items") or soup129        listings: dict[str, Listing] = {}130        for item in carousel.find_all("div", recursive=False):131            try:132                self._parse_item(item, listings)133            except Exception:134                continue135        return list(listings.values())136137    def _parse_item(self, item, listings: dict[str, Listing]) -> None:138        link = item.select_one('a[href*="RentalId="]')139        if not link:140            return141        qs = parse_qs(urlparse(link["href"]).query)142        ext_id = (qs.get("RentalId") or [""])[0]143        if not ext_id or ext_id in listings:144            return145        # unité louée : drapeau rented=1 du lien ou overlay « rented »146        if (qs.get("rented") or ["0"])[0] == "1":147            return148        if item.select_one('img[src*="rented_overlay"]'):149            return150151        h2 = item.find("h2")152        title = h2.get_text(" ", strip=True) if h2 else ""153        title = re.sub(r"\s*\(voir\)\s*$", "", title).strip()154155        # <p>Secteur, Ville<br/><span class="price">890$ par mois, …</span></p>156        price_el = item.select_one("span.price")157        price_label = price_el.get_text(" ", strip=True) if price_el else ""158        location = ""159        p_loc = price_el.find_parent("p") if price_el else item.find("p")160        if p_loc:161            loc_txt = p_loc.get_text("\n", strip=True).split("\n")[0]162            if "$" not in loc_txt:163                location = re.sub(r"\s+", " ", loc_txt).strip()164165        # « Plateau, Hull » -> ville Gatineau (Hull/Aylmer = secteurs fusionnés)166        sector, city = location, ""167        parts = [p.strip() for p in location.split(",") if p.strip()]168        if parts and parts[-1].lower() in _CITIES:169            city = "Gatineau"170            if parts[-1].lower() == "gatineau" and len(parts) > 1:171                sector = ", ".join(parts[:-1])172        elif parts:173            city = parts[-1]174            sector = ", ".join(parts[:-1])175176        # description : les <p> hors ligne secteur/prix177        desc_parts: list[str] = []178        for p in item.find_all("p"):179            txt = re.sub(r"\s+", " ", p.get_text(" ", strip=True))180            if not txt or "$" in txt and price_label and price_label in txt:181                continue182            if txt == location or price_el and price_el in p.descendants:183                continue184            if p is p_loc:185                continue186            desc_parts.append(txt)187        description = "\n".join(desc_parts)[:2500]188189        # type d'unité : Maison/Condo du titre ; pour les appartements, le190        # « n chambres à coucher » de la description (jamais deviné sinon)191        unit_type = normalize_unit_type(title)192        if not re.fullmatch(r"\d½|6½\+|Studio|Loft|Chambre|Maison|Condo",193                            unit_type or ""):194            m = re.search(r"(\d+)\s*chambres?\b", description, re.I)195            unit_type = normalize_unit_type(f"{m.group(1)} chambres") if m else ""196197        # photo : chemin Windows « Rentals\263 Atmosphere\S_IMG.jpg » -> URL198        images: list[str] = []199        for im in item.select("img[src]")[: self.max_images]:200            src = (im.get("src") or "").replace("\\", "/")201            if not src or "rented_overlay" in src or src.startswith("Images/"):202                continue203            if not src.startswith("http"):204                src = f"{BASE}/" + quote(src.lstrip("/"), safe="/")205            if src not in images:206                images.append(src)207208        listings[ext_id] = Listing(209            source=self.source_id,210            external_id=ext_id,211            url=f"{HOME_URL}#location-{ext_id}",212            title=title,213            sector=sector,214            city=city or "Gatineau",215            unit_type=unit_type,216            price_label=price_label,217            description=description,218            images=images,219        )220
Files main
Menu

Theme