SPB Git

Repository Public

cmaq_firecrawl.py 7.4 KB 194 lines python

1#!/usr/bin/env python32# =============================================================================3#                  SP BOUCHER | SOFTWARE & RESEARCH4#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5# =============================================================================6#7# PROJECT METADATA8# -----------------------------------------------------------------------------9# Project          : Fabri·Ka10# File             : scripts/cmaq_firecrawl.py11# Description      : Récolte du répertoire CMAQ (metiersdart.ca) via Firecrawl.12# Module           : scripts13# Repository       : https://git.spboucher.ai/fabri-ka14# Created          : 2026-08-1215# Last Modified    : 2026-08-1216#17# =============================================================================18# AUTHOR & PROFESSIONAL AFFILIATION19# =============================================================================20#21# Author           : Simon-Pierre Boucher22# Position         : Professor of Finance23# Institution      : Université du Québec en Outaouais (UQO)24# Department       : Département des sciences administratives25# Organization     : SP Boucher26#27# Website          : https://spboucher.ai28# Git              : https://git.spboucher.ai29#30# =============================================================================31# OFFICIAL CONTACT DIRECTORY32# =============================================================================33#34# General          : info@spboucher.ai35# Professional     : contact@spboucher.ai36# Direct           : simon@spboucher.ai37# Research         : research@spboucher.ai38# Development      : dev@spboucher.ai39# Support          : support@spboucher.ai40# Security/Admin   : admin@spboucher.ai41# Notifications    : notifications@spboucher.ai42#43# Preferred Contact: contact@spboucher.ai44#45# =============================================================================46# COPYRIGHT & INTELLECTUAL PROPERTY47# =============================================================================48#49# Copyright (c) 202650# Simon-Pierre Boucher51#52# All rights reserved where applicable.53#54# This file is governed by the applicable project license,55# copyright notices, institutional agreements and relevant law.56#57# Unless expressly authorized by the applicable license or58# rights holder, copying, redistribution, sublicensing,59# publication and commercial exploitation are not permitted.60#61# Existing third-party rights and notices remain unaffected.62#63# =============================================================================64# CONFIDENTIALITY & SECURITY65# =============================================================================66#67# Classification   : Public68# Distribution     : Public repository; use is governed by the project license69# Security Contact : admin@spboucher.ai70#71# Access to this source does not independently grant permission72# to redistribute or disclose confidential materials.73#74# Do not embed credentials, private keys, access tokens,75# certificates or confidential personal information.76#77# =============================================================================78# LICENSE & MAINTENANCE79# =============================================================================80#81# License          : None specified (no license file in this repository)82# Maintainer       : Simon-Pierre Boucher83# Technical Contact: dev@spboucher.ai84#85# =============================================================================86# END OF SP BOUCHER SOURCE HEADER87# =============================================================================8889"""Récolte du répertoire CMAQ (metiersdart.ca) via Firecrawl.9091Le répertoire est une app JS à session : la liste des artisans (~1880) n'existe92dans le DOM qu'après soumission du formulaire, paginée 18/page en ordre93ALÉATOIRE par recherche. Stratégie : sessions Firecrawl répétées, chacune94soumet la recherche puis clique « > » N fois en accumulant {cid, name, metier,95org} ; dédup par cid entre sessions jusqu'à saturation.9697Sortie : data/raw/cmaq_artisans.jsonl (+ format harvest pour aggregate.py)98"""99import json100import os101import sys102import time103104import requests105106ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))107OUT = os.path.join(ROOT, "data", "raw", "cmaq_artisans.jsonl")108KEY = os.environ.get("FIRECRAWL_API_KEY", "")109110PAGES_PER_SESSION = int(os.environ.get("CMAQ_PAGES", "40"))111MAX_SESSIONS = int(os.environ.get("CMAQ_SESSIONS", "14"))112STALE_STOP = 2      # arrêt après N sessions sans nouveau cid113114JS = ("(async()=>{const acc=[];const grab=()=>{document.querySelectorAll('.list_rep_arti')"115      ".forEach(c=>{const a=c.querySelector('a[href*=cid]');const n=c.querySelector('h4');"116      "const m=c.querySelector('.artisant_list_metier');const o=c.querySelector('.artisant_list_org');"117      "acc.push({cid:(a?a.href.match(/cid=(\\d+)/):null)?.[1]||null,"118      "name:n?n.textContent.trim():'',metier:m?m.textContent.trim():'',"119      "org:o?o.textContent.trim():''});});};grab();"120      f"for(let i=0;i<{PAGES_PER_SESSION - 1};i++)" + "{"121      "const next=[...document.querySelectorAll('#pagination a.link')]"122      ".find(x=>x.textContent.trim()==='>');if(!next)break;next.click();"123      "await new Promise(r=>setTimeout(r,2200));grab();}"124      "return JSON.stringify(acc);})()")125126PAYLOAD = {127    "url": "https://www.metiersdart.ca/repertoire_artisan.php",128    "formats": ["html"],129    "timeout": 200000,130    "actions": [131        {"type": "wait", "milliseconds": 2500},132        {"type": "click", "selector": "#form_repertoire_membres_form input[type=submit]"},133        {"type": "wait", "milliseconds": 5000},134        {"type": "executeJavascript", "script": JS},135    ],136}137138139def load_seen():140    seen = {}141    if os.path.exists(OUT):142        with open(OUT) as f:143            for line in f:144                try:145                    r = json.loads(line)146                    seen[r["cid"]] = r147                except Exception:148                    pass149    return seen150151152def main():153    if not KEY:154        sys.exit("FIRECRAWL_API_KEY manquant")155    seen = load_seen()156    stale = 0157    for sess in range(1, MAX_SESSIONS + 1):158        try:159            r = requests.post("https://api.firecrawl.dev/v1/scrape",160                              headers={"Authorization": f"Bearer {KEY}",161                                       "Content-Type": "application/json"},162                              json=PAYLOAD, timeout=280)163            d = r.json()164            rets = ((d.get("data") or {}).get("actions") or {}).get("javascriptReturns") or []165            items = []166            for ret in rets:167                v = ret.get("value")168                if isinstance(v, str) and v.startswith("["):169                    items = json.loads(v)170        except Exception as exc:171            print(f"session {sess}: ERREUR {exc}", flush=True)172            time.sleep(10)173            continue174        new = 0175        with open(OUT, "a") as f:176            for it in items:177                cid = it.get("cid")178                if not cid or cid in seen:179                    continue180                seen[cid] = it181                f.write(json.dumps(it, ensure_ascii=False) + "\n")182                new += 1183        print(f"session {sess}: {len(items)} cartes, +{new} nouveaux, total {len(seen)}", flush=True)184        stale = stale + 1 if new == 0 else 0185        if stale >= STALE_STOP:186            print("saturation atteinte", flush=True)187            break188        time.sleep(3)189    print(f"TOTAL artisans CMAQ: {len(seen)}", flush=True)190191192if __name__ == "__main__":193    main()194
Files main
Menu

Theme