A powerful, standalone web scraping toolkit using Playwright and various parsers.
Project description
๐ท๏ธ Web Scraper Toolkit & MCP Server
Expertly Crafted by: Roy Dawson IV
A production-grade, multimodal scraping engine designed for AI Agents. Converts the web into LLM-ready assets (Markdown, JSON, PDF) with robust anti-bot evasion.
๐ The "Why": AI-First Scraping
In the era of Agentic AI, tools need to be more than just Python scripts. They need to be Token-Efficient, Self-Rectifying, and Structured.
โจ Core Design Goals
- ๐ค Hyper Model-Friendly: All tools return standardized JSON Envelopes, separating metadata from content to prevent "context pollution."
- ๐ Intelligent Sitemap Discovery: summary-first approach prevents context flooding. Detects indices, provides counts, and offers keyword deep-search to find specific pages (e.g. "about", "contact") without reading the whole site.
- ๐ก๏ธ Robust Failover: Smart detection of anti-bot challenges (Cloudflare/403s) automatically triggers a switch from Headless to Visible browser mode to pass checks.
- ๐ฏ Precision Control: Use CSS Selectors (
selector) and token limits (max_length) to extract exactly what you need, saving tokens and money. - ๐ Batch Efficiency: The explicit
batch_scrapetool handles parallel processing found in high-performance agent workflows. - โก MCP Native: Exposes a full Model Context Protocol (MCP) server for instant integration with Claude Desktop, Cursor, and other agentic IDEs.
- ๐ Privacy & Stealth: Uses
playwright-stealthand randomized user agents to mimic human behavior.
๐ฆ Installation
Option A: PyPI (Recommended)
Install directly into your environment or agent container.
pip install web-scraper-toolkit
playwright install
Option B: From Source (Developers)
git clone https://github.com/imyourboyroy/WebScraperToolkit.git
cd WebScraperToolkit
pip install -e .
playwright install
๐๏ธ Architecture & Best Practices
We support two distinct integration patterns depending on your needs:
Pattern 1: The "Agentic" Way (MCP Server)
Best for: Claude Desktop, Cursor, Custom Agent Swarms.
- Mechanism: Runs as a standalone process (stdio transport).
- Benefit: True Sandbox. If the browser crashes, your Agent survives.
- Usage: Use
web-scraper-server.
Pattern 2: The "Pythonic" Way (Library)
Best for: data pipelines, cron jobs, tight integration.
- Mechanism: Direct import of
WebCrawler. - Benefit: Simplicity. No subprocess management.
- Safety: Internal scraping logic still uses
ProcessPoolExecutorfor isolation!
๐๏ธ Package Architecture
The codebase follows the Single Responsibility Principle with clean modular organization:
web_scraper_toolkit/
โโโ core/ # Core utilities
โ โโโ state/ # Cache, session, history management
โ โโโ content/ # Text chunking, token counting
โ โโโ automation/ # Form filling, retry logic, utilities
โโโ parsers/ # Content parsing
โ โโโ extraction/ # Contact, metadata, media extraction
โ โโโ search/ # Web search, SERP parsing
โ โโโ sitemap/ # Sitemap discovery and parsing
โโโ browser/ # Playwright browser management
โโโ crawler/ # Autonomous crawler engine (Proxie)
โโโ server/ # MCP server
โ โโโ handlers/ # Request handlers
โ โโโ mcp_tools/ # MCP tool implementations
โโโ playbook/ # Scraping playbook models
โโโ proxie/ # Proxy management
โโโ scraper/ # Low-level fetching engines
Key Design Features:
core/: Centralized utilities with sub-packages for state, content, and automationparsers/: Content parsing with sub-packages for extraction and searchserver/mcp_tools/: Dedicated modules for Scraping, Search, Extraction, and Playbooks- Backward Compatible: All exports available from main package imports
๐ MCP Server Integration
This is the primary way to use the toolkit with AI models. The server runs locally and exposes tools via the Model Context Protocol.
Running the Server
Once installed, simply run:
web-scraper-server --verbose
Connecting to Claude Desktop / Cursor
Add the following to your agent configuration:
{
"mcpServers": {
"web-scraper": {
"command": "web-scraper-server",
"args": ["--verbose"],
"env": {
"SCRAPER_WORKERS": "4"
}
}
}
}
๐ง The "JSON Envelope" Standard
To ensure high reliability for Language Models, all tools return data in this strict JSON format:
{
"status": "success", // or "error"
"meta": {
"url": "https://example.com",
"timestamp": "2023-10-27T10:00:00",
"format": "markdown"
},
"data": "# Markdown Content of the Website..." // The actual payload
}
Why? This allows the model to instantly check .status and handle errors gracefully without hallucinating based on error text mixed with content.
๐ ๏ธ Available MCP Tools (34 Total)
| Tool | Description | Key Args |
|---|---|---|
| Scraping | ||
scrape_url |
The Workhorse. Scrapes a single page. | url, selector (CSS), max_length |
batch_scrape |
The Time Saver. Parallel processing. | urls (List), format |
get_metadata |
Extract JSON-LD, OpenGraph, TwitterCards. | url |
screenshot |
Capture visual state. | url, path |
save_pdf |
High-fidelity PDF renderer. | url, path |
| Discovery | ||
get_sitemap |
Smart Discovery. Auto-filters noise. | url, keywords (e.g. "team"), limit |
crawl_site |
Alias for sitemap discovery. | url |
extract_contacts |
Autonomous Contact Extraction (JSON). | url |
batch_contacts |
Parallel contact extraction (hardware-limited). | urls (List) |
extract_links |
NEW: Extract all hyperlinks from page. | url, filter_external |
| Search & Research | ||
search_web |
Standard Search (DDG/Google). | query |
deep_research |
The Agent. Search + Crawl + Report. | query |
| Form Automation | ||
fill_form |
Login/Form automation. Session persistence. | url, fields (JSON), submit_selector |
extract_tables |
Get structured table data. | url, table_selector |
click_element |
Click elements (JS triggers). | url, selector |
| File Operations | ||
download_file |
Download PDFs, images, files. | url, path |
| Autonomous | ||
run_playbook |
Autonomous Mode. Execute complex JSON playbooks. | playbook_json, proxies_json |
| Health & Validation | ||
health_check |
System status check. | (none) |
validate_url |
Pre-flight URL check. | url |
detect_content_type |
Detect HTML/PDF/image. | url |
| Configuration | ||
configure_scraper |
Browser settings (headless mode). | headless (bool) |
configure_stealth |
Robots.txt opt-out, stealth mode. | respect_robots, stealth_mode |
configure_retry |
Exponential backoff settings. | max_attempts, initial_delay |
get_config |
View current configuration. | (none) |
| Cache Management | ||
clear_cache |
Clear response cache. | (none) |
get_cache_stats |
View cache hits/misses/size. | (none) |
| Session Management | ||
clear_session |
Clear browser session (cookies). | session_id |
new_session |
Start fresh browser session. | (none) |
list_sessions |
List saved sessions. | (none) |
| Content Processing | ||
chunk_text |
Split text for LLM context. | text, max_chunk_size, overlap |
get_token_count |
Estimate token count. | text, model |
truncate_text |
Truncate to token limit. | text, max_tokens |
| History | ||
get_history |
Get scraping history. | limit |
clear_history |
Clear history. | (none) |
Note: By default, the toolkit respects
robots.txt. To bypass (for authorized testing), call:configure_stealth(respect_robots=false)
๐ Intelligent Sitemap Discovery
Unlike standard tools that dump thousands of URLs, this toolkit is designed for Agent Context Windows.
1. Summary First
Returns a structural summary of Sitemaps before extraction.
2. Context-Aware Filtering
Use get_sitemap(url, keywords="contact") to find specific pages without crawling the entire site. The system recursively checks nested sitemaps but filters out low-value content (products, archives) automatically.
๐ Autonomous Contact Extraction
Built-in logic to extract business intelligence from any page.
Capabilities:
- Emails: Decodes Cloudflare-protected emails automatically.
- Phones: Extracts and formats international phone numbers.
- Socials: Identifies social media profiles (LinkedIn, Twitter, etc.).
MCP Usage:
extract_contacts(url="https://example.com/contact")
Example Output:
**Identity**
- Business Name: Busy People
- Author Name: Roy Dawson
**Emails**
- contact@example.com
๐ฆพ Advanced Usage: Autonomous Crawler (Proxie & Playbooks)
For complex, multi-step missions, use the Autonomous Crawler. It combines Playbooks (Strategy) with Proxie (Resilience).
1. Define a Playbook
Create a strictly typed strategy using Playbook and Rule models.
from web_scraper_toolkit.playbook import Playbook, Rule, PlaybookSettings
playbook = Playbook(
name="Forum Scraper",
base_urls=["https://forum.example.com"],
rules=[
# Follow pagination
Rule(type="follow", regex=r"/page-\d+"),
# Extract specific thread data
Rule(type="extract", regex=r"/threads/.*", extract_fields=[
{"name": "title", "selector": "h1.thread-title"},
{"name": "author", "selector": ".username"}
])
],
settings=PlaybookSettings(
respect_robots=True,
validation_enabled=True,
ai_context="Extract user sentiment from forum posts."
)
)
2. Configure Proxies & Resilience
Manage IP rotation and security with ProxieConfig.
from web_scraper_toolkit.proxie import ProxieConfig, ProxyManager, Proxy
# Load settings (can use config.json)
config = ProxieConfig(
enforce_secure_ip=True, # Kill-Switch if Real IP leaks
max_retries=5,
rotation_strategy="health_weighted"
)
# Initialize Manager
manager = ProxyManager(config, proxies=[
Proxy(host="1.2.3.4", port=8080, username="user", password="pass"),
# ...
])
3. Launch Mission
from web_scraper_toolkit.crawler import ProxieCrawler
crawler = ProxieCrawler(playbook, manager)
await crawler.run()
# Results saved to results_Forum_Scraper.jsonl
๐ป CLI Usage (Standalone)
For manual scraping or testing without the MCP server:
# Basic Markdown Extraction (Best for RAG)
web-scraper --url https://example.com --format markdown
# High-Fidelity PDF with Auto-Scroll
web-scraper --url https://example.com --format pdf
# Batch process a list of URLs from a file
web-scraper --input urls.txt --format json --workers 4
# Sitemap to JSON (Site Mapping)
web-scraper --input https://example.com/sitemap.xml --site-tree --format json
๐ ๏ธ CLI Reference
| Option | Shorthand | Description | Default |
|---|---|---|---|
--url |
-u |
Single target URL to scrape. | None |
--input |
-i |
Input file (.txt, .csv, .json, sitemap .xml) or URL. |
None |
--format |
-f |
Output: markdown, pdf, screenshot, json, html. |
markdown |
--headless |
Run browser in headless mode. (Off/Visible by default for stability). | False |
|
--workers |
-w |
Number of concurrent workers. Pass max for CPU - 1. |
1 |
--merge |
-m |
Merge all outputs into a single file. | False |
--contacts |
Autonomously extract emails/phones to output. | False |
|
--site-tree |
Extract URLs from sitemap input without crawling. | False |
|
--verbose |
-v |
Enable verbose logging. | False |
๐ค Python API
Integrate the WebCrawler directly into your Python applications.
import asyncio
from web_scraper_toolkit import WebCrawler, BrowserConfig
async def agent_task():
# 1. Configure
config = BrowserConfig(
headless=True,
timeout=30000
)
# 2. Instantiate
crawler = WebCrawler(config=config)
# 3. Run
results = await crawler.run(
urls=["https://example.com"],
output_format="markdown",
output_dir="./memory"
)
print(results)
if __name__ == "__main__":
asyncio.run(agent_task())
โ๏ธ Global Configuration
The toolkit supports a centralized config.json at the project root for managing defaults across all tools.
Example config.json:
{
"browser": {
"headless": true,
"browser_type": "chromium",
"viewport_width": 1280,
"viewport_height": 800,
"timeout": 30000
},
"parser": {
"ignore_links": false,
"ignore_images": false,
"body_width": 0,
"extract_opengraph": true,
"extract_twitter_cards": true
},
"sitemap": {
"max_concurrent": 4,
"max_depth": 3,
"request_timeout": 15
},
"http": {
"connection_pool_limit": 100,
"connection_per_host": 10,
"dns_cache_ttl": 300,
"total_timeout": 30,
"connect_timeout": 10
},
"retry": {
"max_attempts": 3,
"initial_delay_seconds": 1.0,
"max_delay_seconds": 30.0,
"exponential_base": 2.0,
"jitter": true
},
"proxie": {
"validation_url": "https://httpbin.org/ip",
"timeout_seconds": 10,
"max_concurrent_checks": 50,
"rotation_strategy": "round_robin",
"enforce_secure_ip": true,
"max_retries": 3,
"cooldown_seconds": 300
},
"crawler": {
"default_user_agent": "WebScraperToolkit/1.0 (Crawler)",
"default_max_depth": 3,
"default_max_pages": 100,
"default_crawl_delay": 1.0,
"global_ignore_robots": false,
"request_timeout": 30
},
"playbook": {
"respect_robots": true,
"max_depth": 3,
"max_pages": 100,
"crawl_delay": 1.0,
"ai_context": false,
"validation_enabled": false,
"reuse_rules": true
},
"cache": {
"enabled": true,
"ttl_seconds": 300,
"directory": "./cache",
"max_size_mb": 100
},
"session": {
"persist": true,
"directory": "./sessions",
"reuse_browser": true
},
"chunking": {
"enabled": false,
"max_chunk_size": 8000,
"overlap": 200
},
"temp_directory": "./temp",
"server": {
"name": "Web Scraper Toolkit",
"port": 8000,
"host": "localhost",
"log_level": "INFO"
}
}
This file allows external agents (like Cursor or Claude) to inspect and modify behavioral defaults without code changes.
Server Environment Variables
Override specific server settings via ENV:
| Variable | Description | Default |
|---|---|---|
SCRAPER_WORKERS |
Number of concurrent browser processes. | 1 |
SCRAPER_VERBOSE |
Enable debug logs (true/false). |
false |
โ Verification & Testing
This project includes a comprehensive verification suite to ensure strict configuration enforcement, proxy resilience, and data integrity.
Run the suite:
python tests/verify_suite.py
Example Output (Verified):
+-----------------------------------------------------------------------------+
| Running Test 01: Proxy Resilience (Hail Mary) |
+-----------------------------------------------------------------------------+
โ Proxy Revival Triggered and Succeeded
Verify ProxyManager attempts 'Hail Mary' retry when all proxies are dead. ... ok
+-----------------------------------------------------------------------------+
| Running Test 02: Crawler Integrity (Persistence & Optimization) |
+-----------------------------------------------------------------------------+
โ Persistence Verified (results_IntegrityTest.jsonl)
โ Rule Reuse Optimization Verified
Verify Crawler Rule Reuse and Persistence. ... ok
+-----------------------------------------------------------------------------+
| Running Test 03: BrowserConfig Enforcement |
+-----------------------------------------------------------------------------+
โ BrowserConfig Enforced
Verify WebCrawler strictly enforces BrowserConfig. ... ok
----------------------------------------------------------------------
Ran 3 tests in 2.383s
OK
SUCCESS: All tests passed.
๐ License
MIT License.
Created with โค๏ธ by the Intelligence of Roy Dawson IV.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file web_scraper_toolkit-0.1.7.tar.gz.
File metadata
- Download URL: web_scraper_toolkit-0.1.7.tar.gz
- Upload date:
- Size: 114.3 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
c893c1ff75a6bb1e64fca75e5303add215625f2bbd79ba11706504c42c2e7e46
|
|
| MD5 |
e7f2ea7b61c84d990c266c65cd830ec3
|
|
| BLAKE2b-256 |
912277a977522b0d8d82503b0e05fed79d9821522b94692dc50422362f250f8c
|
Provenance
The following attestation bundles were made for web_scraper_toolkit-0.1.7.tar.gz:
Publisher:
publish.yml on ImYourBoyRoy/WebScraperToolkit
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
web_scraper_toolkit-0.1.7.tar.gz -
Subject digest:
c893c1ff75a6bb1e64fca75e5303add215625f2bbd79ba11706504c42c2e7e46 - Sigstore transparency entry: 774413969
- Sigstore integration time:
-
Permalink:
ImYourBoyRoy/WebScraperToolkit@81eb383d28da7d8157040b1a0deb7a9dd71800ea -
Branch / Tag:
refs/tags/v0.1.7 - Owner: https://github.com/ImYourBoyRoy
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@81eb383d28da7d8157040b1a0deb7a9dd71800ea -
Trigger Event:
push
-
Statement type:
File details
Details for the file web_scraper_toolkit-0.1.7-py3-none-any.whl.
File metadata
- Download URL: web_scraper_toolkit-0.1.7-py3-none-any.whl
- Upload date:
- Size: 125.3 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
45c65c25f0482bda0ef95a39401e594a940d3a9e9a4aa27f76e6ad0b714d9696
|
|
| MD5 |
4602ef4a681032c7d4d32a4cf63a585f
|
|
| BLAKE2b-256 |
c69a4a1a1f67f4c6b4b1bd0fbff7218df7116435f19039eefb8b5a409b86272d
|
Provenance
The following attestation bundles were made for web_scraper_toolkit-0.1.7-py3-none-any.whl:
Publisher:
publish.yml on ImYourBoyRoy/WebScraperToolkit
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
web_scraper_toolkit-0.1.7-py3-none-any.whl -
Subject digest:
45c65c25f0482bda0ef95a39401e594a940d3a9e9a4aa27f76e6ad0b714d9696 - Sigstore transparency entry: 774413970
- Sigstore integration time:
-
Permalink:
ImYourBoyRoy/WebScraperToolkit@81eb383d28da7d8157040b1a0deb7a9dd71800ea -
Branch / Tag:
refs/tags/v0.1.7 - Owner: https://github.com/ImYourBoyRoy
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@81eb383d28da7d8157040b1a0deb7a9dd71800ea -
Trigger Event:
push
-
Statement type: