"""Cotejo de 20 fichas (criterio 7). Red solo en este contenedor; una petición cada 5 s. Descarga la página de origen de
cada lote de /w/muestra.csv y, en la PLACSP, los documentos HTML de «Adjudicación» y «Formalización» (donde están las
ofertas recibidas por lote). Sin reintentos en bucle: cada fallo queda en /w/descargas.csv."""
import csv, html, re, ssl, time, urllib.request, os
UA = 'Mozilla/5.0 (X11; Linux x86_64) buscalicitaciones-cotejo/1.0 (+https://buscalicitaciones.com)'
CTX = ssl.create_default_context(); PAUSA = 5.0
def get(url):
req = urllib.request.Request(url, headers={'User-Agent': UA, 'Accept-Language': 'es-ES,es;q=0.9'})
with urllib.request.urlopen(req, timeout=60, context=CTX) as r:
return r.status, r.read()
def enlaces_docs(s):
out = []
for m in re.finditer(r'
(.*?)
', s, flags=re.S):
fila = m.group(1)
t = re.search(r'tipoDocumento[^>]*>\s*]*>\s*([^<]+)', fila)
a = re.search(r'href="(https://contrataciondelestado\.es/FileSystem/servlet/GetDocumentByIdServlet[^"]+)"', fila)
if t and a and re.match(r'\s*(Adjudicaci|Formalizaci)', t.group(1)):
out.append((t.group(1).strip(), html.unescape(a.group(1))))
return out
filas = list(csv.DictReader(open('/w/muestra.csv')))
out = open('/w/descargas.csv', 'w', newline='')
w = csv.DictWriter(out, fieldnames=['n', 'url', 'estado', 'bytes', 'docs', 'hora'])
w.writeheader()
for r in filas:
base = f"/w/html/{int(r['n']):02d}"
rec = {'n': r['n'], 'url': r['url'], 'estado': '', 'bytes': 0, 'docs': '', 'hora': time.strftime('%Y-%m-%d %H:%M:%S')}
try:
st, data = get(r['url'])
open(base + '.html', 'wb').write(data)
rec['estado'], rec['bytes'] = ('ok' if st == 200 else f'http {st}'), len(data)
if 'contrataciondelestado.es' in r['url']:
docs = enlaces_docs(data.decode('utf-8', 'replace'))
res = []
for i, (tipo, a) in enumerate(docs[:3]):
time.sleep(PAUSA)
try:
st2, d2 = get(a)
open(f'{base}_doc{i}.html', 'wb').write(d2)
res.append(f'{tipo}:{st2}:{len(d2)}')
except Exception as e: # noqa: BLE001
res.append(f'{tipo}:error {type(e).__name__}')
rec['docs'] = ' | '.join(res) or 'sin documentos de adjudicación'
except Exception as e: # noqa: BLE001
rec['estado'] = f'error {type(e).__name__}: {e}'[:200]
w.writerow(rec); out.flush()
print(rec['n'], rec['estado'], rec['bytes'], rec['docs'], flush=True)
time.sleep(PAUSA)
out.close()