"""BU1 · 52 · descarga de fichas (§7d). Uso: 52_fetch.py cid[=url] ... Tope GLOBAL 30 peticiones (cuenta en interno/cotejo/peticiones.csv), pausa 3 s, parada ante 403/429. Guarda el cuerpo en interno/cotejo/html/_.html.""" import csv, os, sys, time, urllib.request, urllib.error P = '/w/interno/cotejo/peticiones.csv'; TOPE = 30 M = {m['cid']: m for m in csv.DictReader(open('/w/interno/cotejo/muestra.csv'))} hechas = list(csv.reader(open(P))) if os.path.exists(P) else [] n = len(hechas) if any(h[3] in ('403', '429') for h in hechas): sys.exit('parada previa por 403/429') fh = open(P, 'a', newline=''); wr = csv.writer(fh) for arg in sys.argv[1:]: if n >= TOPE: print('tope alcanzado'); break cid, _, url = arg.partition('='); url = url or M[cid]['url_origen'] datos = None if url.startswith('POSTES:'): # Andalucía: el buscador de la ficha consulta su índice Elastic por idExpediente ide = url.split(':', 1)[1]; url = 'https://www.juntadeandalucia.es/haciendayadministracionpublica/apl/pdc-front-publico/elastic/sirec_pdc_expedientes/_search' import json as _j; datos = _j.dumps({"query": {"bool": {"must": [{"term": {"idExpediente": int(ide)}}]}}, "size": 5}).encode() req = urllib.request.Request(url, data=datos, headers={'Content-Type': 'application/json', 'Origin': 'https://www.juntadeandalucia.es','User-Agent': 'Mozilla/5.0 (verificación académica de datos abiertos; 1 petición cada 3 s)', 'Accept': 'text/html,application/json;q=0.9,*/*;q=0.8', 'Accept-Language': 'es,ca;q=0.8'}) n += 1; t = time.strftime('%F %T') try: with urllib.request.urlopen(req, timeout=40) as r: cuerpo = r.read(); st = r.status except urllib.error.HTTPError as e: cuerpo = e.read() if hasattr(e, 'read') else b''; st = e.code except Exception as e: cuerpo = repr(e).encode(); st = 'error' f = f'/w/interno/cotejo/html/{cid}_{n:02d}.html'; open(f, 'wb').write(cuerpo) wr.writerow([n, t, cid, st, len(cuerpo), url]); fh.flush(); print(n, cid, st, len(cuerpo), url[:120], flush=True) if st in (403, 429): print('PARADA por', st); break time.sleep(3)