-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscraper.py
More file actions
714 lines (571 loc) · 29.4 KB
/
Copy pathscraper.py
File metadata and controls
714 lines (571 loc) · 29.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
import requests
from bs4 import BeautifulSoup
import click
import csv
import time
import os
from typing import List, Dict
from urllib.parse import urljoin
import json
import re
from datetime import datetime
import pandas as pd
def parse_english_date(date_str: str) -> str:
"""
Convert English date format like 'Fri Mar 06 12:00:00 CET 2026' to DD/MM/YYYY
Args:
date_str: Date string in format 'Day Month DD HH:MM:SS TZ YYYY'
Returns:
Date in format DD/MM/YYYY or None if parsing fails
"""
try:
months = {
'january': '01', 'february': '02', 'march': '03', 'april': '04',
'may': '05', 'june': '06', 'july': '07', 'august': '08',
'september': '09', 'october': '10', 'november': '11', 'december': '12',
'jan': '01', 'feb': '02', 'mar': '03', 'apr': '04', 'may': '05',
'jun': '06', 'jul': '07', 'aug': '08', 'sep': '09', 'oct': '10',
'nov': '11', 'dec': '12'
}
# Pattern: Word (day of week), Word (month) DD HH:MM:SS (timezone) YYYY
pattern = r'(\w+)\s+(\d{1,2})\s+\d{1,2}:\d{1,2}:\d{1,2}\s+\w+\s+(\d{4})'
match = re.search(pattern, date_str)
if match:
month_str = match.group(1).lower()
day = match.group(2)
year = match.group(3)
month = months.get(month_str, None)
if month:
return f"{int(day):02d}/{month}/{year}"
except Exception:
pass
return None
def normalize_date(date_str: str) -> str:
"""
Normalizza la data nel formato DD/MM/YYYY
Gestisce formati con punti (.), trattini (-) o slash (/)
"""
if not date_str:
return None
try:
# Sostituisci separatori comuni con /
clean_date = date_str.replace('.', '/').replace('-', '/').strip()
# Cerca di estrarre giorno, mese, anno
match = re.match(r'(\d{1,2})[/-](\d{1,2})[/-](\d{2,4})', clean_date)
if match:
day, month, year = match.groups()
# Gestione anno a 2 cifre
if len(year) == 2:
year = '20' + year
return f"{int(day):02d}/{int(month):02d}/{year}"
return clean_date
except Exception:
return date_str
class BandiScraper:
"""Web scraper for FVG regional notices and bids"""
def __init__(self, base_url: str):
self.base_url = base_url
self.bandi = []
self.headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}
def get_total_pages(self) -> int:
"""Determine the total number of pages automatically"""
try:
response = requests.get(self.base_url, headers=self.headers, timeout=10)
soup = BeautifulSoup(response.content, 'html.parser')
# Cerca link di paginazione con parametro 'pag='
pagination_links = soup.find_all('a', href=lambda x: x and 'pag=' in x.lower())
max_page = 1 # Almeno c'è la pagina 1
if pagination_links:
for link in pagination_links:
href = link.get('href', '')
# Estrai il numero di pagina dal parametro pag=X
match = re.search(r'pag=(\d+)', href, re.IGNORECASE)
if match:
try:
page_num = int(match.group(1))
max_page = max(max_page, page_num)
except (ValueError, TypeError):
continue
return max_page
except Exception as e:
click.echo(f"Errore nella determinazione delle pagine: {e}", err=True)
return 1 # Default a 1 pagina se c'è errore
def parse_page(self, page_num: int) -> List[Dict]:
"""Parse a single page and extract bandi information"""
bandi_list = []
try:
url = f"{self.base_url}?pag={page_num}"
response = requests.get(url, headers=self.headers, timeout=10)
response.raise_for_status()
soup = BeautifulSoup(response.content, 'html.parser')
# Cerca i box contenenti i bandi
# La struttura HTML usa classi "box-bando"
bando_boxes = soup.find_all('div', class_='box-bando')
if not bando_boxes:
# Prova un approccio alternativo: cerca div con classe "box"
bando_boxes = soup.find_all('div', class_='box')
for box in bando_boxes:
bando = self._extract_bando_from_box(box)
if bando:
bandi_list.append(bando)
return bandi_list
except Exception as e:
click.echo(f"Errore durante l'analisi della pagina {page_num}: {e}", err=True)
return []
def _extract_bando_from_box(self, box) -> Dict:
"""Extract bando info from a box-bando element"""
try:
# Struttura tipica:
# <div class="box-bando">
# <div class="box-header">Data e titolo</div>
# <div class="box-body">Descrizione e link</div>
# </div>
bando = {}
text = box.get_text(strip=True)
if len(text) < 20:
return None
# Estrai data dalla box-header
header = box.find('div', class_='box-header')
if header:
header_text = header.get_text(strip=True)
# Estrai data (formato DD.MM.YYYY o DD/MM/YYYY)
date_match = re.search(r'(\d{1,2}[./-]\d{1,2}[./-]\d{2,4})', header_text)
if date_match:
bando['data'] = normalize_date(date_match.group(1))
# Il titolo è solitamente dopo la data
bando['titolo'] = header_text[date_match.end():].strip() if date_match else header_text[:100]
# Estrai titolo dalla box-titolo
title_elem = box.find('div', class_='box-titolo')
if title_elem:
bando['titolo'] = title_elem.get_text(strip=True)
# Estrai link
link = box.find('a', href=True)
if link:
href = link.get('href')
if href:
bando['link'] = urljoin(self.base_url, href)
# Estrai descrizione dalla box-campo
campo = box.find('div', class_='box-campo')
if campo:
# AUMENTATO IL LIMITE: da 200 a 1000 caratteri per la descrizione breve
bando['descrizione'] = campo.get_text(strip=True)[:1000]
# Cerca scadenza nel testo
scadenza_match = re.search(r'scadenza[:\s]+(\d{1,2}[./-]\d{1,2}[./-]\d{2,4})', text, re.IGNORECASE)
if scadenza_match:
bando['scadenza'] = normalize_date(scadenza_match.group(1))
return bando if len(bando) > 1 else None
except Exception:
return None
def _extract_bando_from_container(self, element) -> Dict:
"""Extract bando info from a container element"""
try:
text = element.get_text(strip=True)
if len(text) < 20:
return None
bando = {}
# Estrai titolo
title_elem = element.find(['h1', 'h2', 'h3', 'h4', 'strong', 'b', 'a'])
if title_elem:
bando['titolo'] = title_elem.get_text(strip=True)
else:
bando['titolo'] = text[:100]
# Estrai link
link_elem = element.find('a', href=True)
if link_elem:
link = link_elem.get('href')
if link:
bando['link'] = urljoin(self.base_url, link)
# Estrai descrizione
desc_elem = element.find('p')
if desc_elem:
desc_text = desc_elem.get_text(strip=True)
if desc_text and len(desc_text) > 10:
bando['descrizione'] = desc_text
# Cerca date
date_pattern = r'\d{1,2}[/-]\d{1,2}[/-]\d{2,4}'
dates = re.findall(date_pattern, text)
if dates:
bando['data'] = normalize_date(dates[0])
if len(dates) > 1:
bando['scadenza'] = normalize_date(dates[-1])
return bando if len(bando) > 1 else None
except Exception:
return None
def scrape_all_pages(self, max_pages: int = None, fetch_details: bool = True) -> List[Dict]:
"""Scrape all pages"""
total_pages = self.get_total_pages()
if max_pages:
total_pages = min(total_pages, max_pages)
click.echo(f"Avvio scraping... Pagine totali: {total_pages}")
for page_num in range(1, total_pages + 1):
try:
click.echo(f"Analisi pagina {page_num}/{total_pages}...", nl=False)
page_bandi = self.parse_page(page_num)
self.bandi.extend(page_bandi)
click.echo(f" ✓ Trovati {len(page_bandi)} bandi")
time.sleep(1)
except Exception as e:
click.echo(f" ✗ Errore: {e}", err=True)
continue
# Ora estrai i dettagli da ogni bando visitando la pagina specifica
if fetch_details:
click.echo(f"\nEstrazione dettagli dalle pagine dei bandi...")
for i, bando in enumerate(self.bandi, 1):
if bando.get('link'):
click.echo(f" [{i}/{len(self.bandi)}] {bando['titolo'][:50]}...", nl=False)
try:
details = self._fetch_bando_details(bando['link'])
# Aggiungi i dettagli al bando
bando.update(details)
click.echo(" ✓")
time.sleep(0.5) # Delay tra richieste
except Exception as e:
click.echo(f" ✗ ({str(e)[:30]})")
continue
click.echo(f"\nTotale bandi scaricati: {len(self.bandi)}")
return self.bandi
def _fetch_bando_details(self, url: str) -> Dict:
"""Fetch detailed information from a bando page"""
try:
response = requests.get(url, headers=self.headers, timeout=15)
response.raise_for_status()
soup = BeautifulSoup(response.content, 'html.parser')
details = {}
# Estrai il testo completo della pagina
all_text = soup.get_text()
# === ESTRAZIONE TITOLO (MIGLIORATA) ===
# Cerca ID specifico del titolo
title_elem_specific = soup.find(id='ctl00_cph_lblTitolo')
if title_elem_specific:
details['titolo_completo'] = title_elem_specific.get_text(strip=True)
# Aggiorna anche il titolo breve se quello estratto dalla lista era troncato
if len(details['titolo_completo']) > len(details.get('titolo', '')):
details['titolo'] = details['titolo_completo']
# === ESTRAZIONE SCADENZA ===
# Primo: Cerca la struttura HTML <span class="box-scadenza">
box_scadenza = soup.find('span', class_='box-scadenza')
if box_scadenza:
box_data = box_scadenza.find('span', class_='box-data')
if box_data:
raw_date = box_data.get_text(strip=True)
# Prova a parsare il formato inglese
parsed_date = parse_english_date(raw_date)
if parsed_date:
details['scadenza'] = normalize_date(parsed_date)
# Secondo: Fallback al pattern regex nel testo
if not details.get('scadenza'):
# Prova pattern: scadenza DD/MM/YYYY o DD.MM.YYYY
scadenza_match = re.search(r'scadenza[:\s]*(\d{1,2}[./-]\d{1,2}[./-]\d{2,4})', all_text, re.IGNORECASE)
if scadenza_match:
details['scadenza'] = normalize_date(scadenza_match.group(1))
# Importo
importo_match = re.search(r'importo[:\s]*€?\s*([\d.,]+(?:\s*euro)?)', all_text, re.IGNORECASE)
if importo_match:
details['importo'] = importo_match.group(1).strip()
# Ufficio/Dipartimento
ufficio_patterns = [
r'(?:ufficio|dipartimento|direzione)[:\s]*([^\n]+)',
r'(?:responsabile|intestatario)[:\s]*([^\n]+)',
]
for pattern in ufficio_patterns:
match = re.search(pattern, all_text, re.IGNORECASE)
if match and not details.get('ufficio'):
details['ufficio'] = match.group(1).strip()[:100]
break
# Descrizione estesa (primi 4000 caratteri di testo utile - limite Excel)
# --- PULIZIA PRELIMINARE DEL SOUP ---
# Crea una copia per non rovinare altre estrazioni
content_soup = BeautifulSoup(str(soup), 'html.parser')
# Rimuovi elementi indesiderati comuni
for noise in content_soup.find_all(['header', 'footer', 'nav', 'script', 'style', 'noscript', 'form']):
noise.extract()
# Rimuovi elementi specifici per data, breadcrumb, avvisi
noise_classes = [
'box-data', 'box-scadenza', 'breadcrumb', 'path', 'menu',
'alert', 'cookie', 'privacy', 'social', 'print', 'torna-indietro',
'box-titolo', 'titolo-pagina', 'data-pubblicazione'
]
for cls in noise_classes:
for tag in content_soup.find_all(class_=lambda x: x and cls in x.lower()):
tag.extract()
# Rimuovi specifico avviso browser
for tag in content_soup.find_all(string=re.compile(r"sito è ottimizzato", re.IGNORECASE)):
parent = tag.parent
if parent:
parent.extract()
text_blocks = []
# Strategia 0 (MIGLIORE): Cerca ID specifico ASP.NET segnalato dall'utente
# Spesso è in uno span o div con id ctl00_cph_lblDescrizione
specific_id_container = content_soup.find(id='ctl00_cph_lblDescrizione')
if specific_id_container:
# Se trovato, è la fonte più affidabile
text = specific_id_container.get_text(separator='\n', strip=True)
if len(text) > 10:
text_blocks = [text]
if not text_blocks:
# Strategia 1: Cerca i paragrafi <p> se sono numerosi e sostanziosi
paragraphs = content_soup.find_all('p')
valid_paragraphs = [p for p in paragraphs if len(p.get_text(strip=True)) > 20]
if len(valid_paragraphs) >= 2:
# Se abbiamo buoni paragrafi, usiamo quelli
text_blocks = [p.get_text(strip=True) for p in valid_paragraphs]
else:
# Strategia 2: Cerca div con classi specifiche
prioritized_classes = ['box-descrizione', 'contenuto', 'box-body', 'corpo-pagina', 'box-content']
potential_containers = content_soup.find_all('div', class_=prioritized_classes)
main_container = None
if potential_containers:
for container in potential_containers:
if len(container.get_text(strip=True)) > 30:
main_container = container
break
if not main_container:
# Fallback su div con più testo
max_len = 0
for div in content_soup.find_all('div'):
if len(div.find_all('div', recursive=False)) > 3:
continue
text_len = len(div.get_text(strip=True))
if text_len > max_len and text_len < 10000:
max_len = text_len
main_container = div
if main_container:
text = main_container.get_text(separator='\n', strip=True)
text_blocks = [text]
# Strategia 3: Se ancora niente, prova body
if not text_blocks:
body = content_soup.find('body')
if body:
text = body.get_text(separator='\n')
lines = [line.strip() for line in text.split('\n') if len(line.strip()) > 50]
text_blocks = lines
if text_blocks and not details.get('descrizione_estesa'):
main_text = '\n'.join(text_blocks)
# PULIZIA FINALE TESTO (Migliorata)
# 1. Rimuovi intestazioni comuni note per duplicarsi
main_text = re.sub(r"Centri per l'impiego\s+Centro per l'impiego di [^\n]+\s*", "", main_text, flags=re.IGNORECASE)
# 2. Rimuovi duplicazioni massicce (se il testo si ripete identico per almeno 50 char)
# Cerca una sottostringa lunga che si ripete
half_len = len(main_text) // 2
if half_len > 50:
first_half = main_text[:half_len]
if first_half in main_text[half_len:]:
# Trovata ripetizione grossolana
main_text = first_half
# 3. Rimuovi date all'inizio
main_text = re.sub(r'^[A-Za-z]{3}\s+[A-Za-z]{3}\s+\d{1,2}.*?\d{4}', '', main_text).strip()
# 4. Rimuovi "documentazione", "CERCA PER" e tutto ciò che segue
stop_words = ['documentazione', 'CERCA PER', 'Torna indietro', 'Attenzione!']
for word in stop_words:
pattern = re.compile(r'\s*' + re.escape(word) + r'.*$', re.IGNORECASE | re.DOTALL)
main_text = pattern.sub('', main_text)
# AUMENTATO IL LIMITE
full_text = main_text[:4000].replace('\n', ' ')
# Rimuovi la parola "contenuto" alla fine
full_text = re.sub(r'\s*contenuto\s*$', '', full_text, flags=re.IGNORECASE)
details['descrizione_estesa'] = full_text.strip()
# --- ESTRAZIONE ALLEGATI ---
files = []
# Strategia 1 (MIGLIORE): Cerca nei box specifici segnalati
# ID noti: ctl00_cph_divAllegati, ctl00_cph_divDocumentazione, ctl00_cph_divProgetti, ctl00_cph_divGraduatorie
# Classe comune: box-documentazione
doc_containers = content_soup.find_all('div', class_='box-documentazione')
# Se non trova per classe, cerca per ID specifici parziali
if not doc_containers:
doc_containers = content_soup.find_all('div', id=re.compile(r'ctl00_cph_div(Allegati|Documentazione|Progetti|Graduatorie)', re.IGNORECASE))
extracted_urls = set() # Per evitare duplicati
if doc_containers:
for container in doc_containers:
# Cerca link dentro questi contenitori
for link in container.find_all('a', href=True):
file_url = link.get('href', '').strip()
file_name = link.get_text(strip=True)
if file_url and file_url not in extracted_urls and not file_url.startswith(('javascript:', '#', 'mailto:')):
full_url = urljoin(url, file_url)
extracted_urls.add(file_url)
files.append({
'nome': file_name[:150], # Aumentato limite nome
'url': full_url
})
# Strategia 2 (FALLBACK): Cerca link PDF/DOC nel resto della pagina se non abbiamo trovato nulla
if not files:
file_links = soup.find_all('a', href=lambda x: x and any(ext in x.lower() for ext in ['.pdf', '.doc', '.docx', '.xls', '.xlsx', '.zip']))
for link in file_links[:5]: # Max 5 file nel fallback
file_url = link.get('href', '').strip()
if file_url and file_url not in extracted_urls:
file_name = link.get_text(strip=True)
full_url = urljoin(url, file_url)
extracted_urls.add(file_url)
files.append({
'nome': file_name[:100],
'url': full_url
})
if files:
details['allegati'] = json.dumps(files, ensure_ascii=False)
return details
except Exception as e:
return {}
def save_to_csv(self, filename: str):
"""Save scraped data to CSV file"""
if not self.bandi:
click.echo("Nessun dato da salvare", err=True)
return
try:
# Create directory if it doesn't exist
directory = os.path.dirname(filename)
if directory:
os.makedirs(directory, exist_ok=True)
# Pulisci e rinomina i dati prima di salvare
export_data = []
for bando in self.bandi:
item = bando.copy()
# Rinomina descrizione_estesa -> descrizione
if 'descrizione_estesa' in item:
item['descrizione'] = item.pop('descrizione_estesa')
elif 'descrizione' not in item:
item['descrizione'] = ''
# Rimuovi colonne non richieste
item.pop('ufficio', None)
item.pop('titolo_completo', None) # Se presente come campo temporaneo
export_data.append(item)
keys = set()
for item in export_data:
keys.update(item.keys())
keys = sorted(list(keys))
with open(filename, 'w', newline='', encoding='utf-8') as f:
writer = csv.DictWriter(f, fieldnames=keys)
writer.writeheader()
writer.writerows(export_data)
click.echo(f"Dati salvati in {filename}")
except Exception as e:
click.echo(f"Errore durante il salvataggio CSV: {e}", err=True)
def save_to_excel(self, filename: str):
"""Save scraped data to Excel file"""
if not self.bandi:
click.echo("Nessun dato da salvare", err=True)
return
try:
# Create directory if it doesn't exist
directory = os.path.dirname(filename)
if directory:
os.makedirs(directory, exist_ok=True)
# Pulisci e rinomina i dati
export_data = []
for bando in self.bandi:
item = bando.copy()
# Rinomina descrizione_estesa -> descrizione
if 'descrizione_estesa' in item:
item['descrizione'] = item.pop('descrizione_estesa')
# Rimuovi colonne non richieste
item.pop('ufficio', None)
item.pop('titolo_completo', None)
export_data.append(item)
# Convert to DataFrame
df = pd.DataFrame(export_data)
# Riordina colonne per leggibilità (se presenti)
desired_order = ['data', 'scadenza', 'titolo', 'descrizione', 'link', 'allegati']
cols = [c for c in desired_order if c in df.columns] + [c for c in df.columns if c not in desired_order]
df = df[cols]
# Save to Excel with formatting
with pd.ExcelWriter(filename, engine='openpyxl') as writer:
df.to_excel(writer, sheet_name='Bandi', index=False)
# Get the workbook and worksheet
workbook = writer.book
worksheet = writer.sheets['Bandi']
# Auto-adjust column widths
for column in worksheet.columns:
max_length = 0
column_letter = column[0].column_letter
for cell in column:
try:
if len(str(cell.value)) > max_length:
max_length = len(str(cell.value))
except:
pass
adjusted_width = min(max_length + 2, 50) # Max 50 characters
worksheet.column_dimensions[column_letter].width = adjusted_width
click.echo(f"Dati salvati in {filename}")
except Exception as e:
click.echo(f"Errore durante il salvataggio Excel: {e}", err=True)
def get_output_folder(self, base_folder: str = 'data') -> str:
"""
Create and return a timestamped output folder
Args:
base_folder: Base folder path (default: 'data')
Returns:
Path to the created timestamped folder
"""
# Create timestamp: YYYY-MM-DD_HH-MM-SS
timestamp = datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
output_folder = os.path.join(base_folder, timestamp)
# Create directory
os.makedirs(output_folder, exist_ok=True)
return output_folder
def save_to_json(self, filename: str):
"""Save scraped data to JSON file"""
if not self.bandi:
click.echo("Nessun dato da salvare", err=True)
return
try:
# Create directory if it doesn't exist
directory = os.path.dirname(filename)
if directory:
os.makedirs(directory, exist_ok=True)
# Pulisci e rinomina i dati
export_data = []
for bando in self.bandi:
item = bando.copy()
# Rinomina descrizione_estesa -> descrizione
if 'descrizione_estesa' in item:
item['descrizione'] = item.pop('descrizione_estesa')
# Rimuovi colonne non richieste
item.pop('ufficio', None)
item.pop('titolo_completo', None)
export_data.append(item)
with open(filename, 'w', encoding='utf-8') as f:
json.dump(export_data, f, ensure_ascii=False, indent=2)
click.echo(f"Dati salvati in {filename}")
except Exception as e:
click.echo(f"Errore durante il salvataggio JSON: {e}", err=True)
@click.command()
@click.option('--url', default='https://www.regione.fvg.it/rafvg/cms/RAFVG/MODULI/bandi_avvisi/',
help='URL base da analizzare')
@click.option('--output-folder', '-o', default='data', help='Cartella base di output (verrà creata una sottocartella con timestamp)')
@click.option('--max-pages', type=int, default=None, help='Numero massimo di pagine da analizzare')
@click.option('--fetch-details', is_flag=True, default=True,
help='Scarica informazioni dettagliate per ogni bando')
@click.option('--no-details', is_flag=True, default=False,
help='Salta il download dei dettagli (più veloce)')
def main(url, output_folder, max_pages, fetch_details, no_details):
"""Scrape FVG region notices and bids"""
click.echo("FVG Bandi e Avvisi Web Scraper")
click.echo("==============================")
click.echo()
scraper = BandiScraper(url)
# Determina se fetchare i dettagli
fetch_details = not no_details
if fetch_details:
click.echo("Modalità: Scraping con informazioni dettagliate")
else:
click.echo("Modalità: Scraping veloce (senza dettagli)")
click.echo()
bandi = scraper.scrape_all_pages(max_pages=max_pages, fetch_details=fetch_details)
if not bandi:
click.echo("Nessun dato scaricato", err=True)
return
# Get timestamped output folder
output_dir = scraper.get_output_folder(output_folder)
# Build output filenames
json_file = os.path.join(output_dir, 'bandi.json')
excel_file = os.path.join(output_dir, 'bandi.xlsx')
# Save in both formats
scraper.save_to_json(json_file)
scraper.save_to_excel(excel_file)
click.echo()
click.echo(f"✓ Cartella output: {output_dir}")
click.echo(f"✓ Totale bandi scaricati: {len(bandi)}")
click.echo()
if __name__ == '__main__':
main()