Improve scraper with retry logic and add sources documentation
Co-authored-by: ArtemFilin1990 <221041513+ArtemFilin1990@users.noreply.github.com>
This commit is contained in:
1 parent
85cc94a3ab
commit
5eb4327dbc
3 files changed
+244
-9
No files matched your search
@@ -0,0 +1,122 @@
|
||||
# Источники данных / Data Sources
|
||||
|
||||
Эта директория содержит исходные данные, скрипты для их сбора и документацию по источникам информации.
|
||||
|
||||
## Содержание
|
||||
|
||||
### Скрипты
|
||||
- **aprom_table_scraper.py** - Скрипт для загрузки таблиц с сайта aprom.by
|
||||
- Поддерживает автоматические повторные попытки при сетевых ошибках
|
||||
- Настраиваемые параметры через CLI или переменные окружения
|
||||
- Независим от внешних зависимостей (только stdlib)
|
||||
- См. `python aprom_table_scraper.py --help` для деталей
|
||||
|
||||
### Данные
|
||||
- **aprom_brands.json** - База производителей подшипников (284 записи)
|
||||
- Источник: [aprom.by/brands.php](https://aprom.by/brands.php)
|
||||
- Дата выгрузки: 2025-12-28
|
||||
- Схема данных: см. `aprom_brands_schema.json`
|
||||
|
||||
- **aprom_brands_schema.json** - JSON Schema для расширенной базы производителей
|
||||
- Определяет структуру данных для информации о брендах
|
||||
- Поддерживает дополнительные поля: категория, сайт, сертификации
|
||||
|
||||
### Документация источников
|
||||
- **literature.md** - Список литературы и стандартов
|
||||
- **online_catalogs.md** - Онлайн-каталоги производителей
|
||||
- **offline_catalog_snapshots.md** - Документация по локальным копиям каталогов
|
||||
- **RAW_INDEX.md** - Индекс сырых данных и выгрузок
|
||||
|
||||
### Каталоги производителей
|
||||
Директория `vendor_catalogs/` содержит описания и метаданные каталогов:
|
||||
- Обзоры структуры каталогов
|
||||
- Снимки состояния онлайн-каталогов
|
||||
- Методики извлечения данных
|
||||
|
||||
## Использование скрипта aprom_table_scraper.py
|
||||
|
||||
### Базовое использование
|
||||
```bash
|
||||
python sources/aprom_table_scraper.py --output sources/aprom_table_data.json
|
||||
```
|
||||
|
||||
### С настройкой повторных попыток
|
||||
```bash
|
||||
python sources/aprom_table_scraper.py \
|
||||
--output sources/aprom_table_data.json \
|
||||
--max-retries 5 \
|
||||
--retry-delay 3.0 \
|
||||
--verbose
|
||||
```
|
||||
|
||||
### Через переменные окружения
|
||||
```bash
|
||||
export APROM_MAX_RETRIES=5
|
||||
export APROM_RETRY_DELAY=3.0
|
||||
export HTTP_TIMEOUT_SECONDS=15
|
||||
python sources/aprom_table_scraper.py --output sources/aprom_table_data.json
|
||||
```
|
||||
|
||||
### Параметры
|
||||
- `--url` - URL для загрузки (по умолчанию: https://aprom.by/table.php)
|
||||
- `--output` - Путь для сохранения JSON
|
||||
- `--timeout` - Таймаут запроса в секундах
|
||||
- `--delay` - Задержка между запросами
|
||||
- `--max-pages` - Максимальное количество страниц
|
||||
- `--max-retries` - Максимальное количество повторных попыток
|
||||
- `--retry-delay` - Задержка между повторными попытками
|
||||
- `-v, --verbose` - Увеличить детализацию логов
|
||||
|
||||
## Тестирование
|
||||
|
||||
Запуск unit-тестов для скрипта:
|
||||
```bash
|
||||
python tests/test_aprom_scraper.py
|
||||
```
|
||||
|
||||
Или с pytest:
|
||||
```bash
|
||||
python -m pytest tests/test_aprom_scraper.py -v
|
||||
```
|
||||
|
||||
## Версионирование источников
|
||||
|
||||
При обновлении каталогов производителей рекомендуется:
|
||||
|
||||
1. Сохранять дату получения данных
|
||||
2. Указывать версию каталога или дату публикации
|
||||
3. Вычислять контрольную сумму файлов
|
||||
4. Документировать изменения в changelog
|
||||
|
||||
Пример метаданных:
|
||||
```json
|
||||
{
|
||||
"source": "aprom.by/brands.php",
|
||||
"retrieved_at": "2025-12-28T18:00:00Z",
|
||||
"checksum_sha256": "...",
|
||||
"version": "2025-12-28",
|
||||
"record_count": 284
|
||||
}
|
||||
```
|
||||
|
||||
## Вклад в источники
|
||||
|
||||
При добавлении новых источников:
|
||||
|
||||
1. Документируйте источник в соответствующем .md файле
|
||||
2. Указывайте точную ссылку и дату доступа
|
||||
3. Для PDF/каталогов указывайте версию и издателя
|
||||
4. Сохраняйте исходные данные в неизменном виде
|
||||
5. Скрипты обработки храните отдельно от данных
|
||||
|
||||
## Стандарты качества
|
||||
|
||||
Все данные должны:
|
||||
- ✅ Иметь указание источника
|
||||
- ✅ Включать дату получения/проверки
|
||||
- ✅ Соответствовать структуре репозитория
|
||||
- ✅ Быть проверяемыми (ссылки доступны, версии указаны)
|
||||
|
||||
---
|
||||
|
||||
**Последнее обновление**: 2025-12-28
|
||||
@@ -0,0 +1,69 @@
|
||||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"title": "Bearing Brands Database Schema",
|
||||
"description": "Schema for bearing manufacturer and brand information",
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"required": ["name", "country", "description"],
|
||||
"properties": {
|
||||
"name": {
|
||||
"type": "string",
|
||||
"description": "Official brand or manufacturer name"
|
||||
},
|
||||
"country": {
|
||||
"type": "string",
|
||||
"description": "Country of origin or primary manufacturing location"
|
||||
},
|
||||
"description": {
|
||||
"type": "string",
|
||||
"description": "Brief description of products and specialization"
|
||||
},
|
||||
"category": {
|
||||
"type": "string",
|
||||
"enum": ["premium", "standard", "budget", "specialized", "unknown"],
|
||||
"description": "Quality/price category (optional)"
|
||||
},
|
||||
"website": {
|
||||
"type": "string",
|
||||
"format": "uri",
|
||||
"description": "Official website URL (optional)"
|
||||
},
|
||||
"product_categories": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"bearings",
|
||||
"linear_motion",
|
||||
"seals",
|
||||
"belts",
|
||||
"chains",
|
||||
"couplings",
|
||||
"gears",
|
||||
"lubricants",
|
||||
"tools",
|
||||
"other"
|
||||
]
|
||||
},
|
||||
"description": "List of product categories offered (optional)"
|
||||
},
|
||||
"certifications": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
},
|
||||
"description": "Quality certifications (ISO, GOST, etc.) (optional)"
|
||||
},
|
||||
"source": {
|
||||
"type": "string",
|
||||
"description": "Source of information (e.g., aprom.by, official catalog)"
|
||||
},
|
||||
"last_updated": {
|
||||
"type": "string",
|
||||
"format": "date",
|
||||
"description": "Date when information was last verified (YYYY-MM-DD)"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,10 +11,14 @@ configurable via CLI flags or environment variables:
|
||||
REQUEST_DELAY_SECONDS - delay between pages in seconds (default: 0.2)
|
||||
APROM_MAX_PAGES - hard cap for visited pages (default: 250)
|
||||
APROM_SCRAPER_USER_AGENT - optional override for the HTTP User-Agent
|
||||
APROM_MAX_RETRIES - maximum retry attempts for failed requests (default: 3)
|
||||
APROM_RETRY_DELAY - delay between retry attempts in seconds (default: 2.0)
|
||||
|
||||
Example:
|
||||
python sources/aprom_table_scraper.py \\
|
||||
--output sources/aprom_table_data.json
|
||||
--output sources/aprom_table_data.json \\
|
||||
--max-retries 5 \\
|
||||
--retry-delay 3.0
|
||||
|
||||
If network access is blocked, the script will log a warning and exit without
|
||||
creating or altering the output file.
|
||||
@@ -41,6 +45,8 @@ DEFAULT_TIMEOUT_SECONDS = int(os.getenv("HTTP_TIMEOUT_SECONDS", "10"))
|
||||
DEFAULT_DELAY_SECONDS = float(os.getenv("REQUEST_DELAY_SECONDS", "0.2"))
|
||||
DEFAULT_MAX_PAGES = int(os.getenv("APROM_MAX_PAGES", "250"))
|
||||
DEFAULT_USER_AGENT = os.getenv("APROM_SCRAPER_USER_AGENT", "BazaApromScraper/1.0")
|
||||
DEFAULT_MAX_RETRIES = int(os.getenv("APROM_MAX_RETRIES", "3"))
|
||||
DEFAULT_RETRY_DELAY = float(os.getenv("APROM_RETRY_DELAY", "2.0"))
|
||||
|
||||
|
||||
def configure_logging(verbosity: int) -> None:
|
||||
@@ -201,10 +207,25 @@ def table_to_records(table: List[List[TableCell]]) -> List[Dict[str, str]]:
|
||||
return records
|
||||
|
||||
|
||||
def fetch_html(url: str, timeout: int) -> str:
|
||||
def fetch_html(url: str, timeout: int, max_retries: int = DEFAULT_MAX_RETRIES, retry_delay: float = DEFAULT_RETRY_DELAY) -> str:
|
||||
"""Fetch HTML with retry logic for transient network errors."""
|
||||
request = Request(url, headers={"User-Agent": DEFAULT_USER_AGENT})
|
||||
with urlopen(request, timeout=timeout) as response:
|
||||
return response.read().decode(response.headers.get_content_charset("utf-8"), errors="replace")
|
||||
last_error = None
|
||||
|
||||
for attempt in range(max_retries):
|
||||
try:
|
||||
with urlopen(request, timeout=timeout) as response:
|
||||
return response.read().decode(response.headers.get_content_charset("utf-8"), errors="replace")
|
||||
except (HTTPError, URLError) as error:
|
||||
last_error = error
|
||||
if attempt < max_retries - 1:
|
||||
logging.warning("Attempt %d/%d failed for %s: %s. Retrying in %.1fs...",
|
||||
attempt + 1, max_retries, url, error, retry_delay)
|
||||
time.sleep(retry_delay)
|
||||
else:
|
||||
logging.error("All %d attempts failed for %s: %s", max_retries, url, error)
|
||||
|
||||
raise last_error
|
||||
|
||||
|
||||
def crawl_all_pages(
|
||||
@@ -212,21 +233,26 @@ def crawl_all_pages(
|
||||
timeout_seconds: int,
|
||||
delay_seconds: float,
|
||||
max_pages: int,
|
||||
max_retries: int = DEFAULT_MAX_RETRIES,
|
||||
retry_delay: float = DEFAULT_RETRY_DELAY,
|
||||
) -> List[Dict[str, str]]:
|
||||
visited: Set[str] = set()
|
||||
queue: Deque[str] = deque([normalize_url(base_url)])
|
||||
aggregated_rows: List[Dict[str, str]] = []
|
||||
failed_urls: List[str] = []
|
||||
|
||||
while queue and len(visited) < max_pages:
|
||||
url = queue.popleft()
|
||||
if url in visited:
|
||||
continue
|
||||
logging.info("Fetching %s", url)
|
||||
logging.info("Fetching %s (page %d/%d)", url, len(visited) + 1, max_pages)
|
||||
try:
|
||||
html = fetch_html(url, timeout_seconds)
|
||||
html = fetch_html(url, timeout_seconds, max_retries, retry_delay)
|
||||
except (HTTPError, URLError) as error:
|
||||
logging.warning("Failed to fetch %s: %s", url, error)
|
||||
break
|
||||
logging.warning("Failed to fetch %s after %d retries: %s", url, max_retries, error)
|
||||
failed_urls.append(url)
|
||||
# Continue to next URL instead of breaking
|
||||
continue
|
||||
visited.add(url)
|
||||
tables = extract_tables(html)
|
||||
primary_table = select_primary_table(tables)
|
||||
@@ -243,6 +269,9 @@ def crawl_all_pages(
|
||||
|
||||
time.sleep(delay_seconds)
|
||||
|
||||
if failed_urls:
|
||||
logging.warning("Failed to fetch %d URLs: %s", len(failed_urls), failed_urls[:5])
|
||||
|
||||
return aggregated_rows
|
||||
|
||||
|
||||
@@ -296,6 +325,18 @@ def parse_args(argv: Sequence[str]) -> argparse.Namespace:
|
||||
default=0,
|
||||
help="Increase log verbosity (can be repeated)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--max-retries",
|
||||
type=int,
|
||||
default=DEFAULT_MAX_RETRIES,
|
||||
help="Maximum number of retry attempts for failed requests (default: %(default)s)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--retry-delay",
|
||||
type=float,
|
||||
default=DEFAULT_RETRY_DELAY,
|
||||
help="Delay between retry attempts in seconds (default: %(default)s)",
|
||||
)
|
||||
return parser.parse_args(argv)
|
||||
|
||||
|
||||
@@ -303,17 +344,20 @@ def main(argv: Sequence[str]) -> int:
|
||||
args = parse_args(argv)
|
||||
configure_logging(args.verbose)
|
||||
logging.info(
|
||||
"Starting crawl: url=%s, max_pages=%d, timeout=%ds, delay=%.2fs",
|
||||
"Starting crawl: url=%s, max_pages=%d, timeout=%ds, delay=%.2fs, max_retries=%d",
|
||||
args.url,
|
||||
args.max_pages,
|
||||
args.timeout,
|
||||
args.delay,
|
||||
args.max_retries,
|
||||
)
|
||||
rows = crawl_all_pages(
|
||||
base_url=args.url,
|
||||
timeout_seconds=args.timeout,
|
||||
delay_seconds=args.delay,
|
||||
max_pages=args.max_pages,
|
||||
max_retries=args.max_retries,
|
||||
retry_delay=args.retry_delay,
|
||||
)
|
||||
if not rows:
|
||||
logging.warning("No rows extracted; output file will not be created.")
|
||||
|
||||
Reference in new issue
Block a user