-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.py
More file actions
64 lines (52 loc) · 2.11 KB
/
parser.py
File metadata and controls
64 lines (52 loc) · 2.11 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
import requests
import re
import psycopg2
import os
from bs4 import BeautifulSoup
# Подключение к БД (пароль из переменных окружения)
conn = psycopg2.connect(
dbname="parser_db",
user="postgres",
password=os.getenv('DB_PASSWORD', 'localhost_only'),
host="localhost"
)
cursor = conn.cursor()
# Читаем список сайтов из файла
with open('sites.txt', 'r') as file:
urls = [line.strip() for line in file if line.strip()]
headers = {'User-Agent': 'Mozilla/5.0'}
print(f"Начинаем парсинг {len(urls)} сайтов...\n")
for url in urls:
try:
print(f"Парсим: {url}")
# Запрос к сайту
response = requests.get(url, headers=headers, timeout=10)
response.encoding = 'utf-8'
soup = BeautifulSoup(response.text, 'html.parser')
# Извлекаем заголовок
title = soup.title.text.strip() if soup.title else "—"
# Ищем телефон
text = soup.get_text()
phones = re.findall(r'\+7\s?\(?\d{3}\)?\s?\d{3}[-\s]?\d{2}[-\s]?\d{2}', text)
phone = phones[0] if phones else "—"
# Проверка на дубли
cursor.execute("SELECT id FROM sites WHERE url = %s", (url,))
if cursor.fetchone() is None:
cursor.execute(
"INSERT INTO sites (url, title, phone) VALUES (%s, %s, %s)",
(url, title, phone)
)
conn.commit()
print(f" ✓ Сохранено: {title[:50]}... | {phone}")
else:
print(f" ⊙ {url} уже есть в базе, пропускаем")
except requests.exceptions.Timeout:
print(f" ✗ Ошибка: таймаут (сайт не отвечает)")
except requests.exceptions.ConnectionError:
print(f" ✗ Ошибка: не удалось подключиться")
except Exception as e:
print(f" ✗ Ошибка: {e}")
print()
cursor.close()
conn.close()
print("✅ Парсинг завершён!")