-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
100 lines (84 loc) · 3.37 KB
/
app.py
File metadata and controls
100 lines (84 loc) · 3.37 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
from flask import Flask, request, jsonify
from flask_cors import CORS
import requests
from bs4 import BeautifulSoup
import re
from urllib.parse import urljoin
# Inizializza Flask
app = Flask(__name__)
CORS(app) # Abilita il CORS per accettare richieste da qualsiasi dominio
# User-Agent personalizzato
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
}
EMAIL_REGEX = r"[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+"
PHONE_REGEX = r"\b(?:\+?\d{1,3})?[-.\s()]?\d{2,4}[-.\s()]?\d{3,4}[-.\s()]?\d{3,4}\b"
# Funzione per verificare numeri validi
def is_valid_phone(phone):
digits = re.sub(r"\D", "", phone)
return len(digits) >= 8 and len(digits) <= 15
# Funzione per trovare la pagina Contatti
def find_contact_page(url):
try:
response = requests.get(url, headers=headers, timeout=10)
response.raise_for_status()
soup = BeautifulSoup(response.text, "html.parser")
for a_tag in soup.find_all("a", href=True):
href = a_tag["href"]
if "contact" in href.lower() or "contatti" in href.lower():
return urljoin(url, href)
except Exception as e:
print(f"Errore nel trovare la pagina di contatto: {str(e)}")
pass
return url # Torna l'URL originale se non trova nulla
# Funzione per estrarre email e numeri di telefono da una specifica area della pagina
def extract_contacts_from_section(section_html):
emails = set(re.findall(EMAIL_REGEX, section_html))
phones = set(re.findall(PHONE_REGEX, section_html))
valid_phones = {phone for phone in phones if is_valid_phone(phone)}
return emails, valid_phones
# Funzione principale per estrarre contatti
def extract_contacts_from_url(url):
try:
contact_url = find_contact_page(url)
print(f"Trovata pagina di contatto: {contact_url}") # Stampa la pagina trovata
response = requests.get(contact_url, headers=headers, timeout=15)
response.raise_for_status()
soup = BeautifulSoup(response.text, "html.parser")
# Inizializza i risultati
emails, phones = set(), set()
# Cerca nella pagina contatti
page_emails, page_phones = extract_contacts_from_section(soup.get_text())
emails.update(page_emails)
phones.update(page_phones)
print(f"Emails trovate: {emails}") # Stampa le email trovate
print(f"Telefoni trovati: {phones}") # Stampa i numeri di telefono trovati
return {
"URL": url,
"Emails": list(emails),
"Phones": list(phones),
}
except Exception as e:
print(f"Errore nell'estrazione dei dati per {url}: {str(e)}")
return {
"URL": url,
"Emails": [],
"Phones": [],
"Error": str(e),
}
# Endpoint per la home page
@app.route('/')
def home():
return "<h1>Benvenuto nel backend Flask!</h1><p>Il server è attivo e funzionante.</p>"
# Endpoint per processare i link
@app.route('/process-links', methods=['POST'])
def process_links():
data = request.json
urls = data.get("links", [])
if not urls:
return jsonify({"error": "No links provided"}), 400
results = [extract_contacts_from_url(url) for url in urls]
return jsonify(results)
# Avvia il server
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8000)