"""LT1 ยท descarga BOE con tope global de 40 peticiones y pausa de 3 s. Uso: 90_fetch.py nombre=url [nombre=url ...]""" import sys, time, urllib.request, os, csv, datetime LOG = '/w/fuentes_boe/peticiones.csv' n = sum(1 for _ in open(LOG)) - 1 if os.path.exists(LOG) else 0 new = not os.path.exists(LOG) f = open(LOG, 'a', newline=''); w = csv.writer(f) if new: w.writerow(['n', 'hora', 'nombre', 'url', 'estado', 'bytes']) for arg in sys.argv[1:]: nombre, url = arg.split('=', 1) if n >= 40: print('TOPE 40 alcanzado'); break n += 1 hdr = {'User-Agent': 'buscalicitaciones-investigacion/1.0', 'Accept': 'application/xml' if '/texto' in url else 'application/json' if 'datosabiertos' in url else 'application/xml, text/html, */*'} try: r = urllib.request.urlopen(urllib.request.Request(url, headers=hdr), timeout=60); b = r.read(); st = r.status except Exception as e: b = str(e).encode(); st = getattr(e, 'code', 'ERR') open(f'/w/fuentes_boe/{nombre}', 'wb').write(b) w.writerow([n, datetime.datetime.now().isoformat(timespec='seconds'), nombre, url, st, len(b)]); f.flush() print(n, st, nombre, len(b), flush=True) time.sleep(3)