"""VC1 · 52 · descarga de fichas públicas para el cotejo (d): como mucho 30 peticiones, 3 s de pausa, parada ante 403/429. Uso (anfitrión, con red): python3 -I py/52_fetch.py """ import csv, os, ssl, sys, time, urllib.request, urllib.error W = sys.argv[1]; UA = 'Mozilla/5.0 (X11; Linux x86_64) buscalicitaciones-cotejo/1.0 (+https://buscalicitaciones.com)' CTX = ssl.create_default_context(); PAUSA = 3.0; CUPO = 30 logp = f'{W}/interno/cotejo/peticiones.csv'; nuevo = not os.path.exists(logp) log = open(logp, 'a', newline=''); w = csv.writer(log) if nuevo: w.writerow(['n', 'hora', 'clave', 'url', 'estado', 'bytes']) hechas = 0 if nuevo else sum(1 for _ in open(logp)) - 1 for fila in csv.DictReader(open(f'{W}/interno/cotejo/lista_fichas.csv')): dest = f"{W}/{fila['destino']}" if os.path.exists(dest) and os.path.getsize(dest) > 0: continue if hechas >= CUPO: print('CUPO'); break time.sleep(PAUSA) req = urllib.request.Request(fila['url'], headers={'User-Agent': UA, 'Accept-Language': 'es-ES,es;q=0.9'}) try: with urllib.request.urlopen(req, timeout=60, context=CTX) as r: st, body = r.status, r.read() except urllib.error.HTTPError as e: st, body = e.code, e.read() except Exception as e: st, body = f'error {type(e).__name__}', b'' hechas += 1; w.writerow([hechas, time.strftime('%F %T'), fila['clave'], fila['url'], st, len(body)]); log.flush() if body: open(dest, 'wb').write(body) print(hechas, fila['clave'], st, len(body), flush=True) if st in (403, 429): print('PARADA', st); break