SPB Git

Repository Public

kijiji.py 12.3 KB 298 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Immo·Ka9# File             : immoka/connectors/kijiji.py10# Module           : immoka11# Repository       : https://git.spboucher.ai/immo-ka12# Created          : 2026-08-1213# Last Modified    : 2026-08-1814#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# Immo-Ka — Agrégateur de maisons à vendre (province de Québec)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# connectors/kijiji.py : Kijiji (kijiji.ca) — petites annonces immobilières91#   UNIQUEMENT les catégories immobilier À VENDRE, UNIQUEMENT le Québec (l9001) :92#     c35  maisons à vendre · c643 condos à vendre · c641 terrains à vendre93#   Les pages listent 40+ annonces dans __NEXT_DATA__ (Apollo state) avec titre,94#   prix, GPS, adresse et vignette — aucune API privée nécessaire.95# -----------------------------------------------------------------------------96from __future__ import annotations9798import json99import os100import re101102from ..schema import PropertyListing103from .base import BaseConnector104105from . import _detailutil as du106107BASE = "https://www.kijiji.ca"108# (code catégorie, segment d'URL, type canonique)109CATEGORIES = [110    (35, "b-maison-a-vendre", "Maison"),111    (643, "b-condo-a-vendre", "Condo"),112    (641, "b-terrain-a-vendre", "Terrain"),113]114MAX_PAGES = int(os.environ.get("IMMOKA_KIJIJI_MAX_PAGES", "100"))115DETAIL_LIMIT = int(os.environ.get("IMMOKA_KIJIJI_DETAIL_LIMIT", "400"))116117# attributs Apollo (canonicalName) -> libellé FR. Les attributs absents de la118# table gardent leur `name` Kijiji d'origine dans details.119_ATTR_LABELS = {120    "numberbedrooms": "Chambres", "numberbathrooms": "Salles de bain",121    "areainfeet": "Superficie (pi²)", "sizesqft": "Superficie (pi²)",122    "areainacres": "Superficie du terrain",   # texte libre : « 26 acres », « 35 000 pi2 »…123    "yearbuilt": "Année de construction", "forsalebyhousing": "À vendre par",124    "numberparkingspots": "Stationnements", "parkingincluded": "Stationnement inclus",125    "unittype": "Type d'unité", "furnished": "Meublé",126    "virtualtour": "Visite virtuelle", "videochat": "Visite par vidéo",127}128129_ACRES_RE = re.compile(r"([\d\s,.]+)\s*(?:acres?\b|ac\.?$)", re.I)130131132def _lot_sqft_from_free_text(val: str) -> float | None:133    """Superficie de terrain depuis le champ libre « Size (acres) » de Kijiji :134    « 26 acres », « 35 000 pi2 », « 1586 mètre carré », ou un nombre nu (acres)."""135    from ..normalize import parse_area_sqft, parse_float136    t = (val or "").replace("pieds carres", "pi²").replace("pieds carrés", "pi²") \137        .replace("pied carré", "pi²").replace("mètres carrés", "m²") \138        .replace("mètre carré", "m²").replace("metre carre", "m²")139    t = re.sub(r"(\d),(\d{3})\b", r"\1\2", t)     # « 18,000 » = milliers, pas décimale140    v = parse_area_sqft(t)                    # unités pi²/m² explicites141    if v:142        return v143    m = _ACRES_RE.search(t)144    n = parse_float(m.group(1)) if m else None145    if n is None and re.fullmatch(r"[\d\s,.]+", t.strip()):146        n = parse_float(t)                    # nombre nu = acres (nom du champ)147    if n and 0 < n < 1000:148        return round(n * 43560)               # acres -> pi²149    return None150151152def _parse_kijiji_detail(html: str) -> dict:153    """Fiche Kijiji : description complète, attributs, galerie haute résolution."""154    m = re.search(155        r'<script id="__NEXT_DATA__" type="application/json">(.*?)</script>',156        html, re.S)157    if not m:158        return {}159    try:160        data = json.loads(m.group(1))161    except ValueError:162        return {}163    apollo = data.get("props", {}).get("pageProps", {}).get("__APOLLO_STATE__", {})164    it = next((v for k, v in apollo.items()165               if k.startswith("StandardListing:") and isinstance(v, dict)166               and v.get("description")), None)167    if not it:168        return {}169    out: dict = {}170    if it.get("description"):171        out["description"] = str(it["description"]).strip()[:6000]172    imgs = [re.sub(r"rule=kijijica-\d+-\w+", "rule=kijijica-1600-jpg", u)173            for u in it.get("imageUrls") or []]174    if imgs:175        out["images"] = imgs176    features, details = [], {}177    for a in (it.get("attributes") or {}).get("all") or []:178        cn = a.get("canonicalName") or ""179        val = ", ".join(str(v) for v in a.get("values") or [])180        if not val:181            continue182        label = _ATTR_LABELS.get(cn, a.get("name") or cn)183        features.append(f"{label} : {val}")184        details[label] = val185        if cn == "numberbedrooms" and val.isdigit():186            out["bedrooms"] = int(val)187        elif cn == "numberbathrooms":188            mn = re.search(r"\d+", val)       # « 1.5 » -> 1189            if mn:190                out["bathrooms"] = int(mn.group(0))191        elif cn in ("areainfeet", "sizesqft"):192            mn = re.search(r"[\d.]+", val.replace(",", ""))193            if mn:194                out["area_sqft"] = float(mn.group(0))195        elif cn == "areainacres":196            lot = _lot_sqft_from_free_text(val)197            if lot:198                out["lot_sqft"] = lot199        elif cn == "yearbuilt" and val.isdigit():200            out["year_built"] = int(val)201    if features:202        out["features"] = features203    if details:204        out["details"] = details205    loc = it.get("location") or {}206    addr = (loc.get("address") or "").replace(", Canada", "")207    if re.match(r"\s*\d", addr):208        out["address"] = addr.split(",")[0]209    return out210211212class KijijiConnector(BaseConnector):213    source_id = "kijiji"214    request_delay = 1.2215216    def _next_data(self, html: str) -> dict:217        m = re.search(218            r'<script id="__NEXT_DATA__" type="application/json">(.*?)</script>',219            html, re.S)220        return json.loads(m.group(1)) if m else {}221222    def _page(self, seg: str, cat: int, page: int) -> list[dict]:223        """Annonces (Apollo state) d'une page de catégorie."""224        path = (f"{seg}/quebec/c{cat}l9001" if page == 1225                else f"{seg}/quebec/page-{page}/c{cat}l9001")226        html = self.get(f"{BASE}/{path}").text227        data = self._next_data(html)228        apollo = (data.get("props", {}).get("pageProps", {})229                  .get("__APOLLO_STATE__", {}))230        return [v for k, v in apollo.items()231                if k.startswith("StandardListing:") and isinstance(v, dict)]232233    def _to_listing(self, it: dict, ptype: str) -> PropertyListing | None:234        lid = str(it.get("id") or "")235        url = it.get("url") or ""236        if not lid or not url:237            return None238        price = None239        pr = it.get("price") or {}240        if isinstance(pr, dict) and pr.get("amount"):241            price = round(pr["amount"] / 100.0, 0)   # cents → $242            if price < 5000:      # prix bidon fréquent sur Kijiji (1 $, 123 $…)243                price = None244        loc = it.get("location") or {}245        coords = loc.get("coordinates") or {}246        address = (loc.get("address") or "").replace(", Canada", "")247        # « Saint-Hubert, QC J3Y 6Y3 » → ville avant la 1re virgule248        city = loc.get("name") or (address.split(",")[0] if address else "")249        images = []250        for u in it.get("imageUrls") or []:251            images.append(re.sub(r"rule=kijijica-\d+-", "rule=kijijica-640-", u))252        details = {}253        # date de mise en ligne : activationDate = 1re publication (sortingDate254        # est re-bumpée par les remontées/TOP AD)255        posted = str(it.get("activationDate") or it.get("sortingDate") or "")256        if re.match(r"\d{4}-\d{2}-\d{2}", posted):257            details["listed_at"] = posted[:10]258        return PropertyListing(259            source=self.source_id,260            external_id=lid,261            url=url,262            title=it.get("title") or "",263            address=address.split(",")[0] if re.match(r"\s*\d", address) else "",264            city=city,265            property_type=ptype,266            price=price,267            price_label=f"{price:,.0f} $".replace(",", " ") if price else "",268            description=(it.get("description") or "")[:2000],269            details=details,270            images=images,271            lat=coords.get("latitude"),272            lng=coords.get("longitude"),273            broker_name="Kijiji (particuliers)",274            agency="Kijiji Québec",275        )276277    def fetch(self) -> list[PropertyListing]:278        out: dict[str, PropertyListing] = {}279        for cat, seg, ptype in CATEGORIES:280            for page in range(1, MAX_PAGES + 1):281                try:282                    items = self._page(seg, cat, page)283                except Exception:284                    break285                fresh = 0286                for it in items:287                    lst = self._to_listing(it, ptype)288                    if lst is not None and lst.uid not in out:289                        out[lst.uid] = lst290                        fresh += 1291                # plus rien de neuf (page de fin remplie de topAds répétés)292                if fresh == 0 or len(items) < 10:293                    break294        listings = list(out.values())295        # v2 = _ATTR_LABELS étendus (terrain/stationnement/année…) + lot_sqft296        du.enrich(self, listings, DETAIL_LIMIT, _parse_kijiji_detail, key="v2")297        return listings298
Files main
Menu

Theme