"""Segunda pasada del cotejo: el XML (CODICE) de los anuncios de adjudicación de los lotes de licitaciones con varios lotes (el HTML no da las ofertas recibidas por lote) y un intento con la API del portal catalán. 5 s entre peticiones.""" import html, re, ssl, time, urllib.request, json UA = 'Mozilla/5.0 (X11; Linux x86_64) buscalicitaciones-cotejo/1.0 (+https://buscalicitaciones.com)' CTX = ssl.create_default_context() def get(url, acc='*/*'): req = urllib.request.Request(url, headers={'User-Agent': UA, 'Accept': acc, 'Accept-Language': 'es-ES,es;q=0.9'}) try: with urllib.request.urlopen(req, timeout=60, context=CTX) as r: return r.status, r.read() except urllib.error.HTTPError as e: return e.code, e.read() log = open('/w/descargas2.csv', 'w') for n in (2, 6, 8, 10, 12): s = open(f'/w/html/{n:02d}.html', encoding='utf-8', errors='replace').read() k = 0 for m in re.finditer(r'(.*?)', s, flags=re.S): t = re.search(r'tipoDocumento[^>]*>\s*]*>\s*([^<]+)', m.group(1)) tipo = html.unescape(t.group(1)).strip() if t else '' if not re.match(r'(Adjudicaci|Anuncio de Adjudicaci|Resoluci|Desiert|Desistimiento|Renuncia)', tipo): continue xml = [html.unescape(a) for a, alt in re.findall(r'href="([^"]+)"[^>]*>\s*]*alt="([^"]+)"', m.group(1)) if 'xml' in alt.lower()] if not xml: continue st, d = get(xml[0]); open(f'/w/html/{n:02d}_xml{k}.xml', 'wb').write(d) log.write(f'{n},{tipo},{st},{len(d)}\n'); log.flush(); print(n, tipo, st, len(d), flush=True) k += 1; time.sleep(5) if k >= 3: break for n, idp in ((7, '300641915'),): for url in (f'https://contractaciopublica.cat/portal-api/detall-publicacio/{idp}',): st, d = get(url, 'application/json'); open(f'/w/html/{n:02d}_api.json', 'wb').write(d) log.write(f'{n},{url},{st},{len(d)}\n'); log.flush(); print(n, url, st, len(d), d[:200], flush=True) time.sleep(5) log.close()