Skip to main content

Sync-First бібліотека для побудови графу веб-сайтів - просто як requests!

Project description

GraphCrawler

Python License: MIT Version Performance

Python бібліотека для сканування веб-сайтів та побудови графу їх структури.

🚀 Python 3.14 Optimizations

GraphCrawler 4.0 оптимізований для Python 3.14 з підтримкою free-threading:

  • 2-4x швидше HTML парсинг (free-threading)
  • 🚀 3.2x швидше end-to-end crawling
  • 📉 16% менше memory usage
  • ⏱️ 30% швидший startup

Free-threading Mode (рекомендовано)

# Увімкнути free-threading для максимальної швидкості
export PYTHON_GIL=0
python your_script.py

Встановлення

pip install -e .

Optional dependencies

# Playwright driver (для JavaScript сайтів)
pip install -e ".[playwright]"

# Векторизація тексту (плагін)
pip install -e ".[embeddings]"

# Content extractors (плагіни)
pip install -e ".[articles]"

# MongoDB/PostgreSQL storage
pip install -e ".[mongodb,postgresql]"

# Все разом
pip install -e ".[all]"

Швидкий старт

import graph_crawler as gc

# Синхронний API (рекомендовано)
graph = gc.crawl("https://example.com")

print(f"Знайдено {len(graph.nodes)} сторінок")
print(f"Знайдено {len(graph.edges)} посилань")

API

Sync API

import graph_crawler as gc

# Функція crawl()
graph = gc.crawl(
    "https://example.com",
    max_depth=3,        # Максимальна глибина (default: 3)
    max_pages=100,      # Максимум сторінок (default: 100)
    same_domain=True,   # Тільки поточний домен (default: True)
    timeout=300,        # Таймаут в секундах
    request_delay=0.5,  # Затримка між запитами (default: 0.5)
    driver="http",      # "http", "async", "playwright"
)

# Клас Crawler (reusable)
with gc.Crawler(max_depth=3) as crawler:
    graph1 = crawler.crawl("https://site1.com")
    graph2 = crawler.crawl("https://site2.com")

Async API

import asyncio
import graph_crawler as gc

async def main():
    # Функція async_crawl()
    graph = await gc.async_crawl("https://example.com")
    
    # Клас AsyncCrawler (паралельний краулінг)
    async with gc.AsyncCrawler() as crawler:
        graphs = await asyncio.gather(
            crawler.crawl("https://site1.com"),
            crawler.crawl("https://site2.com"),
        )
    return graphs

graphs = asyncio.run(main())

Операції з графом

# Статистика
stats = graph.get_stats()
# {'total_nodes': 47, 'scanned_nodes': 45, 'total_edges': 156, ...}

# Пошук вузла
node = graph.get_node_by_url("https://example.com/page")

# Операції над графами
merged = graph1 + graph2      # Об'єднання
diff = graph2 - graph1        # Різниця
common = graph1 & graph2      # Перетин

# Порівняння
if graph1 < graph2:
    print("graph1 є підграфом graph2")

# Експорт
graph.export_edges("edges.json", format="json")
graph.export_edges("edges.csv", format="csv")
graph.export_edges("graph.dot", format="dot")

URL Rules

from graph_crawler import crawl, URLRule

rules = [
    URLRule(pattern=r".*\.pdf$", should_scan=False),     # Ігнорувати PDF
    URLRule(pattern=r"/products/", priority=10),         # Високий пріоритет
    URLRule(pattern=r"/admin/", should_scan=False),      # Ігнорувати admin
]

graph = crawl("https://example.com", url_rules=rules)

Плагіни

from graph_crawler import crawl, BaseNodePlugin, NodePluginType

class CustomPlugin(BaseNodePlugin):
    @property
    def name(self):
        return "custom_plugin"
    
    @property
    def plugin_type(self):
        return NodePluginType.ON_HTML_PARSED
    
    def execute(self, context):
        # context.html_tree - BeautifulSoup об'єкт
        # context.extracted_links - список посилань
        # context.user_data - словник для даних
        images = context.html_tree.find_all('img')
        context.user_data['image_count'] = len(images)
        return context

graph = crawl("https://example.com", plugins=[CustomPlugin()])

Драйвери

Драйвер Опис Використання
http Async HTTP (aiohttp) Статичні сайти (default)
async Alias для http Зворотня сумісність
playwright Браузер з JS рендерингом JavaScript сайти
# HTTP драйвер (default)
graph = gc.crawl("https://example.com", driver="http")

# Playwright для JavaScript сайтів
graph = gc.crawl("https://spa-example.com", driver="playwright")

Storage

Storage Опис Рекомендовано для
memory В пам'яті < 1,000 сторінок
json JSON файл 1,000 - 20,000 сторінок
sqlite SQLite база 20,000+ сторінок
postgresql PostgreSQL Великі проекти
mongodb MongoDB Великі проекти

Структура проекту

graph_crawler/
├── api/              # Simple API (crawl, Crawler, async_crawl)
├── client/           # GraphCrawlerClient
├── core/             # Node, Edge, Graph, Events, Models
├── crawler/          # Spider, Scheduler, LinkProcessor, Filters
├── drivers/          # HTTP, Playwright драйвери
├── storage/          # Memory, JSON, SQLite, PostgreSQL, MongoDB
├── plugins/          # Node плагіни (vectorization, content_extractors)
├── middleware/       # Rate limiting, Retry, Robots.txt, Proxy
├── factories/        # Driver, Storage factories
├── containers/       # Dependency Injection containers
├── adapters/         # BeautifulSoup adapter
├── exporters/        # JSON, CSV, DOT exporters
└── utils/            # URL utils, DNS cache, Bloom filter

Тестування

pytest
pytest --cov=package_crawler

Вимоги

  • Python 3.11+ (мінімальна версія)
  • Залежності: див. requirements.txt

Яку версію Python обрати?

Версія Рекомендовано для Примітки
3.14 Максимальна швидкість Free-threading (GIL=0), ~3.2x швидше
3.12-3.13 Візуалізація з коробки Стабільні залежності (pyvis, networkx)
3.11 Сумісність Всі функції працюють

Рекомендації для Python 3.14

# Free-threading для максимальної швидкості (рекомендовано)
export PYTHON_GIL=0

# JIT compiler (увімкнено за замовчуванням)
export PYTHON_JIT=1

# Запуск
python your_crawler.py

Очікувані результати:

  • GIL enabled: ~115 pages/sec
  • GIL disabled (free-threading): ~320 pages/sec (3.2x швидше!)

⚠️ Примітка: Деякі залежності візуалізації (pyvis, plotly) можуть бути нестабільні на Python 3.14. Якщо потрібна візуалізація з коробки — використовуйте Python 3.12 або 3.13.

Ліцензія

MIT

Автор

0-EternalJunior-0

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

graph_crawler-4.0.3.tar.gz (603.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

graph_crawler-4.0.3-py3-none-any.whl (762.8 kB view details)

Uploaded Python 3

File details

Details for the file graph_crawler-4.0.3.tar.gz.

File metadata

  • Download URL: graph_crawler-4.0.3.tar.gz
  • Upload date:
  • Size: 603.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.1

File hashes

Hashes for graph_crawler-4.0.3.tar.gz
Algorithm Hash digest
SHA256 46b83d49e05838e553f8f33cf62fb3d9f05f2e2940b4a47cc1de36c07bee1f7b
MD5 228e539dd37c9ae34a04d9f6f457d958
BLAKE2b-256 fc94e88edb9845e595c825f87f2ebf7e51f3545eb7e0d5ac76ac3e79943798bc

See more details on using hashes here.

File details

Details for the file graph_crawler-4.0.3-py3-none-any.whl.

File metadata

  • Download URL: graph_crawler-4.0.3-py3-none-any.whl
  • Upload date:
  • Size: 762.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.1

File hashes

Hashes for graph_crawler-4.0.3-py3-none-any.whl
Algorithm Hash digest
SHA256 183d48c88bbf838f55a5f96095c98111041686c2be93e6281a4ad12277963a79
MD5 85ae2e7b0ee73c1a2bfaec23285ef206
BLAKE2b-256 e4fc64a1c518078937b0e80e6a66983cc29db68da6de7b4f027d34f6774567e4

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page