"""Cotejo §7.4 (red solo para esto): descarga la ficha de origen de cada menor de cotejo/muestra.csv, una petición cada 5 s, y la guarda en cotejo/html/_.. Por fuente: - MADRID_CAM, GALICIA, EUSKADI, VALENCIA (enlace a la PLACSP): la página de url_origen; - ANDALUCIA: la API del buscador que sirve la página (Elasticsearch de pdc-front-publico, la que lee el scraper); - CATALUNYA_PSCP: el JSON de la publicación (url_json del crudo, cotejo/pscp_json.csv); - CATALUNYA (RPC) y CATALUNYA_GENERALITAT: la API de datos abiertos (Socrata hb6v-jcbf y qjue-2pk9). Sin reintentos en bucle: un fallo queda en cotejo/descargas.csv.""" import csv, json, os, ssl, time, urllib.parse, urllib.request UA = 'Mozilla/5.0 (X11; Linux x86_64) buscalicitaciones-cotejo/1.0 (+https://buscalicitaciones.com)' CTX = ssl.create_default_context() PAUSA = 5.0 AND_ES = 'https://www.juntadeandalucia.es/haciendayadministracionpublica/apl/pdc-front-publico/elastic/sirec_pdc_expedientes/_search' SOC = 'https://analisi.transparenciacatalunya.cat/resource/{}.json?' def get(url, body=None, headers=None): h = {'User-Agent': UA, 'Accept-Language': 'es-ES,es;q=0.9'} h.update(headers or {}) req = urllib.request.Request(url, data=body, headers=h, method='POST' if body else 'GET') with urllib.request.urlopen(req, timeout=60, context=CTX) as r: return r.status, r.read() pscp = {r['id_canonical']: r['url_json'] for r in csv.DictReader(open('/w/cotejo/pscp_json.csv'))} filas = list(csv.DictReader(open('/w/cotejo/muestra.csv'))) n_f = {} out = open('/w/cotejo/descargas.csv', 'w', newline='') w = csv.DictWriter(out, fieldnames=['fuente', 'n', 'id_canonical', 'peticion', 'estado', 'bytes', 'fichero', 'hora']) w.writeheader() for r in filas: f = r['fuente']; n_f[f] = n_f.get(f, 0) + 1; n = n_f[f] idc = r['id_canonical']; partes = idc.split(':', 2)[2].split('|') body, headers, ext = None, None, 'html' if f == 'ANDALUCIA': url = AND_ES; ext = 'json' body = json.dumps({'query': {'bool': {'must': [{'match': {'idExpediente': int(partes[0])}}]}}, 'size': 3}).encode() headers = {'Content-Type': 'application/json', 'Accept': 'application/json, text/plain, */*', 'Origin': 'https://www.juntadeandalucia.es', 'Referer': 'https://www.juntadeandalucia.es/haciendayadministracionpublica/apl/pdc-front-publico/perfiles-licitaciones/buscador-general'} elif f == 'CATALUNYA_PSCP': url = pscp.get(idc); ext = 'json' elif f == 'CATALUNYA': q = f"id_organisme_contractant='{partes[0]}' AND codi_expedient='{partes[1]}'" url = SOC.format('hb6v-jcbf') + urllib.parse.urlencode({'$where': q, '$limit': 50}); ext = 'json' elif f == 'CATALUNYA_GENERALITAT': q = f"codi_d_expedient='{partes[1]}'" url = SOC.format('qjue-2pk9') + urllib.parse.urlencode({'$where': q, '$limit': 50}); ext = 'json' else: url = r['url_origen'] fich = f'/w/cotejo/html/{f}_{n:02d}.{ext}' rec = {'fuente': f, 'n': n, 'id_canonical': idc, 'peticion': url, 'estado': '', 'bytes': 0, 'fichero': fich, 'hora': time.strftime('%Y-%m-%d %H:%M:%S')} if not url: rec['estado'] = 'sin url' else: try: st, data = get(url, body, headers) open(fich, 'wb').write(data) rec['estado'], rec['bytes'] = ('ok' if st == 200 else f'http {st}'), len(data) except Exception as e: # noqa: BLE001 rec['estado'] = f'error {type(e).__name__}: {e}'[:200] time.sleep(PAUSA) w.writerow(rec); out.flush() print(f, n, rec['estado'], rec['bytes'], flush=True) out.close()