高级用法(3/3)
Overview
Crawl4AI offers two powerful anti-bot features to help you access websites with bot detection:
- Stealth Mode - Uses playwright-stealth to modify browser fingerprints and behaviors
- Undetected Browser Mode - Advanced browser adapter with deep-level patches for sophisticated bot detection
This guide covers both features and helps you choose the right approach for your needs.
Anti-Bot Features Comparison
| Feature | Regular Browser | Stealth Mode | Undetected Browser |
|---|---|---|---|
| WebDriver Detection | ❌ | ✅ | ✅ |
| Navigator Properties | ❌ | ✅ | ✅ |
| Plugin Emulation | ❌ | ✅ | ✅ |
| CDP Detection | ❌ | Partial | ✅ |
| Deep Browser Patches | ❌ | ❌ | ✅ |
| Performance Impact | None | Minimal | Moderate |
| Setup Complexity | None | None | Minimal |
When to Use Each Approach
Use Regular Browser + Stealth Mode When:
- Sites have basic bot detection (checking navigator.webdriver, plugins, etc.)
- You need good performance with basic protection
- Sites check for common automation indicators
Use Undetected Browser When:
- Sites employ sophisticated bot detection services (Cloudflare, DataDome, etc.)
- Stealth mode alone isn't sufficient
- You're willing to trade some performance for better evasion
Best Practice: Progressive Enhancement
- Start with: Regular browser + Stealth mode
- If blocked: Switch to Undetected browser
- If still blocked: Combine Undetected browser + Stealth mode
Stealth Mode
Stealth mode is the simpler anti-bot solution that works with both regular and undetected browsers:
from crawl4ai import AsyncWebCrawler, BrowserConfig
# Enable stealth mode with regular browser
browser_config = BrowserConfig(
enable_stealth=True, # Simple flag to enable
headless=False # Better for avoiding detection
)
async with AsyncWebCrawler(config=browser_config) as crawler:
result = await crawler.arun("https://example.com")
What Stealth Mode Does:
- Removes
navigator.webdriverflag - Modifies browser fingerprints
- Emulates realistic plugin behavior
- Adjusts navigator properties
- Fixes common automation leaks
Undetected Browser Mode
For sites with sophisticated bot detection that stealth mode can't bypass, use the undetected browser adapter:
Key Features
- Drop-in Replacement: Uses the same API as regular browser mode
- Enhanced Stealth: Built-in patches to evade common detection methods
- Browser Adapter Pattern: Seamlessly switch between regular and undetected modes
- Automatic Installation:
crawl4ai-setupinstalls all necessary browser dependencies
Quick Start
import asyncio
from crawl4ai import (
AsyncWebCrawler,
BrowserConfig,
CrawlerRunConfig,
UndetectedAdapter
)
from crawl4ai.async_crawler_strategy import AsyncPlaywrightCrawlerStrategy
async def main():
# Create the undetected adapter
undetected_adapter = UndetectedAdapter()
# Create browser config
browser_config = BrowserConfig(
headless=False, # Headless mode can be detected easier
verbose=True,
)
# Create the crawler strategy with undetected adapter
crawler_strategy = AsyncPlaywrightCrawlerStrategy(
browser_config=browser_config,
browser_adapter=undetected_adapter
)
# Create the crawler with our custom strategy
async with AsyncWebCrawler(
crawler_strategy=crawler_strategy,
config=browser_config
) as crawler:
# Your crawling code here
result = await crawler.arun(
url="https://example.com",
config=CrawlerRunConfig()
)
print(result.markdown[:500])
asyncio.run(main())
Combining Both Features
For maximum evasion, combine stealth mode with undetected browser:
from crawl4ai import AsyncWebCrawler, BrowserConfig, UndetectedAdapter
from crawl4ai.async_crawler_strategy import AsyncPlaywrightCrawlerStrategy
# Create browser config with stealth enabled
browser_config = BrowserConfig(
enable_stealth=True, # Enable stealth mode
headless=False
)
# Create undetected adapter
adapter = UndetectedAdapter()
# Create strategy with both features
strategy = AsyncPlaywrightCrawlerStrategy(
browser_config=browser_config,
browser_adapter=adapter
)
async with AsyncWebCrawler(
crawler_strategy=strategy,
config=browser_config
) as crawler:
result = await crawler.arun("https://protected-site.com")
Examples
Example 1: Basic Stealth Mode
import asyncio
from crawl4ai import AsyncWebCrawler, BrowserConfig, CrawlerRunConfig
async def test_stealth_mode():
# Simple stealth mode configuration
browser_config = BrowserConfig(
enable_stealth=True,
headless=False
)
async with AsyncWebCrawler(config=browser_config) as crawler:
result = await crawler.arun(
url="https://bot.sannysoft.com",
config=CrawlerRunConfig(screenshot=True)
)
if result.success:
print("✓ Successfully accessed bot detection test site")
# Save screenshot to verify detection results
if result.screenshot:
import base64
with open("stealth_test.png", "wb") as f:
f.write(base64.b64decode(result.screenshot))
print("✓ Screenshot saved - check for green (passed) tests")
asyncio.run(test_stealth_mode())
Example 2: Undetected Browser Mode
import asyncio
from crawl4ai import (
AsyncWebCrawler,
BrowserConfig,
CrawlerRunConfig,
UndetectedAdapter
)
from crawl4ai.async_crawler_strategy import AsyncPlaywrightCrawlerStrategy
async def main():
# Create browser config
browser_config = BrowserConfig(
headless=False,
verbose=True,
)
# Create the undetected adapter
undetected_adapter = UndetectedAdapter()
# Create the crawler strategy with the undetected adapter
crawler_strategy = AsyncPlaywrightCrawlerStrategy(
browser_config=browser_config,
browser_adapter=undetected_adapter
)
# Create the crawler with our custom strategy
async with AsyncWebCrawler(
crawler_strategy=crawler_strategy,
config=browser_config
) as crawler:
# Configure the crawl
crawler_config = CrawlerRunConfig(
markdown_generator=DefaultMarkdownGenerator(
content_filter=PruningContentFilterLXML()
),
capture_console_messages=True, # Test adapter console capture
)
# Test on a site that typically detects bots
print("Testing undetected adapter...")
result: CrawlResult = await crawler.arun(
url="https://www.helloworld.org",
config=crawler_config
)
print(f"Status: {result.status_code}")
print(f"Success: {result.success}")
print(f"Console messages captured: {len(result.console_messages or [])}")
print(f"Markdown content (first 500 chars):\n{result.markdown.raw_markdown[:500]}")
if __name__ == "__main__":
asyncio.run(main())
Browser Adapter Pattern
The undetected browser support is implemented using an adapter pattern, allowing seamless switching between different browser implementations:
# Regular browser adapter (default)
from crawl4ai import PlaywrightAdapter
regular_adapter = PlaywrightAdapter()
# Undetected browser adapter
from crawl4ai import UndetectedAdapter
undetected_adapter = UndetectedAdapter()
The adapter handles: - JavaScript execution - Console message capture - Error handling - Browser-specific optimizations
Best Practices
- Avoid Headless Mode: Detection is easier in headless mode
browser_config = BrowserConfig(headless=False)
- Use Reasonable Delays: Don't rush through pages
crawler_config = CrawlerRunConfig(
wait_time=3.0, # Wait 3 seconds after page load
delay_before_return_html=2.0 # Additional delay
)
- Rotate User Agents: You can customize user agents
browser_config = BrowserConfig(
headers={"User-Agent": "your-user-agent"}
)
- Handle Failures Gracefully: Some sites may still detect and block
if not result.success:
print(f"Crawl failed: {result.error_message}")
Advanced Usage Tips
Progressive Detection Handling
async def crawl_with_progressive_evasion(url):
# Step 1: Try regular browser with stealth
browser_config = BrowserConfig(
enable_stealth=True,
headless=False
)
async with AsyncWebCrawler(config=browser_config) as crawler:
result = await crawler.arun(url)
if result.success and "Access Denied" not in result.html:
return result
# Step 2: If blocked, try undetected browser
print("Regular + stealth blocked, trying undetected browser...")
adapter = UndetectedAdapter()
strategy = AsyncPlaywrightCrawlerStrategy(
browser_config=browser_config,
browser_adapter=adapter
)
async with AsyncWebCrawler(
crawler_strategy=strategy,
config=browser_config
) as crawler:
result = await crawler.arun(url)
return result
Installation
The undetected browser dependencies are automatically installed when you run:
crawl4ai-setup
This command installs all necessary browser dependencies for both regular and undetected modes.
Limitations
- Performance: Slightly slower than regular mode due to additional patches
- Headless Detection: Some sites can still detect headless mode
- Resource Usage: May use more resources than regular mode
- Not 100% Guaranteed: Advanced anti-bot services are constantly evolving
Troubleshooting
Browser Not Found
Run the setup command:
crawl4ai-setup
Detection Still Occurring
Try combining with other features:
crawler_config = CrawlerRunConfig(
simulate_user=True, # Add user simulation
magic=True, # Enable magic mode
wait_time=5.0, # Longer waits
)
Performance Issues
If experiencing slow performance:
# Use selective undetected mode only for protected sites
if is_protected_site(url):
adapter = UndetectedAdapter()
else:
adapter = PlaywrightAdapter() # Default adapter
Future Plans
Note: In future versions of Crawl4AI, we may enable stealth mode and undetected browser by default to provide better out-of-the-box success rates. For now, users should explicitly enable these features when needed.
Conclusion
Crawl4AI provides flexible anti-bot solutions:
- Start Simple: Use regular browser + stealth mode for most sites
- Escalate if Needed: Switch to undetected browser for sophisticated protection
- Combine for Maximum Effect: Use both features together when facing the toughest challenges
Remember: - Always respect robots.txt and website terms of service - Use appropriate delays to avoid overwhelming servers - Consider the performance trade-offs of each approach - Test progressively to find the minimum necessary evasion level
See Also
- Advanced Features - Overview of all advanced features
- Proxy & Security - Using proxies with anti-bot features
- Session Management - Maintaining sessions across requests
- Identity Based Crawling - Additional anti-detection strategies
- Anti-Bot Detection & Fallback - Automatic retry and proxy escalation when blocking is detected
When crawling sites protected by anti-bot systems (Akamai, Cloudflare, PerimeterX, DataDome, Imperva, etc.), requests often get blocked with CAPTCHAs, 403 responses, or empty pages. Crawl4AI provides a layered retry and fallback system that automatically detects blocking and escalates through multiple strategies until content is retrieved.
How Detection Works
After each crawl attempt, Crawl4AI inspects the HTTP status code and HTML content for known anti-bot signals:
- HTTP 403/429 with short or empty response bodies
- Challenge pages — Cloudflare "Just a moment", Akamai "Access Denied", PerimeterX block pages
- CAPTCHA injection — reCAPTCHA, hCaptcha, or vendor-specific challenges on otherwise empty pages
- Firewall blocks — Imperva/Incapsula resource iframes, Sucuri firewall pages, Cloudflare error codes
Detection uses structural HTML markers (specific element IDs, script sources, form actions) rather than generic keywords to minimize false positives. A normal page that happens to mention "CAPTCHA" or "Cloudflare" in its content will not be flagged.
When all attempts fail and blocking is still detected, the result is returned with success=False and error_message describing the block reason.
Configuration Options
All anti-bot retry options live on CrawlerRunConfig:
| Parameter | Type | Default | Description |
|---|---|---|---|
proxy_config |
ProxyConfig, list[ProxyConfig], or None |
None |
Single proxy or ordered list of proxies to try. Each retry round iterates through the full list. Use "direct" or ProxyConfig.DIRECT in a list to explicitly try without a proxy. |
max_retries |
int |
0 |
Number of retry rounds when blocking is detected. 0 = no retries. |
fallback_fetch_function |
async (str) -> str |
None |
Async function called as last resort. Takes URL, returns raw HTML. |
Escalation Chain
Each retry round tries every proxy in proxy_config in order. If all rounds are exhausted and the page is still blocked, the fallback fetch function is called as a last resort.
For each round (1 + max_retries rounds):
1. Try proxy_config[0] (or direct if proxy_config is None)
2. If blocked → try proxy_config[1]
3. If blocked → try proxy_config[2]
4. ... continue through all proxies
5. If any attempt succeeds → done
If all rounds exhausted and still blocked:
6. Call fallback_fetch_function(url) → process returned HTML
Worst-case attempts before the fetch function: (1 + max_retries) x len(proxy_config)
Crawl Stats
Every crawl result includes a crawl_stats dict with detailed attempt tracking:
result.crawl_stats = {
"attempts": 3, # total browser attempts made
"retries": 1, # retry rounds used (0 = succeeded first round)
"proxies_used": [ # ordered list of every attempt
{"proxy": None, "status_code": 403, "blocked": True, "reason": "Akamai block (Reference #)"},
{"proxy": "proxy.io:8080", "status_code": 403, "blocked": True, "reason": "Akamai block (Reference #)"},
{"proxy": "premium.io:9090", "status_code": 200, "blocked": False, "reason": ""},
],
"fallback_fetch_used": False, # whether fallback_fetch_function was called
"resolved_by": "proxy", # "direct" | "proxy" | "fallback_fetch" | null (all failed)
}
Usage Examples
Simple Retry (No Proxy)
Retry the crawl up to 3 times when blocking is detected. Useful when blocks are intermittent or IP-based.
from crawl4ai import AsyncWebCrawler
from crawl4ai.async_configs import BrowserConfig, CrawlerRunConfig
async with AsyncWebCrawler(config=BrowserConfig(headless=True)) as crawler:
result = await crawler.arun(
url="https://example.com",
config=CrawlerRunConfig(max_retries=3),
)
Single Proxy
Pass a single ProxyConfig — it's used on every attempt. Same behavior as always.
from crawl4ai.async_configs import ProxyConfig
config = CrawlerRunConfig(
max_retries=2,
proxy_config=ProxyConfig(
server="http://proxy.example.com:8080",
username="user",
password="pass",
),
)
Direct-First, Then Proxies
Try without a proxy first, then escalate to proxies if blocked. Use ProxyConfig.DIRECT (or the string "direct") in the list to represent a no-proxy attempt.
config = CrawlerRunConfig(
max_retries=1,
proxy_config=[
ProxyConfig.DIRECT, # Try without proxy first
ProxyConfig(
server="http://datacenter-proxy.example.com:8080",
username="user",
password="pass",
),
ProxyConfig(
server="http://residential-proxy.example.com:9090",
username="user",
password="pass",
),
],
)
With this setup, each round tries direct first, then datacenter, then residential. With max_retries=1, worst case is 2 rounds x 3 steps = 6 attempts.
Proxy List (Escalation)
Pass a list of proxies. They're tried in order — first one that works wins. Within each retry round, the entire list is tried again.
config = CrawlerRunConfig(
max_retries=1,
proxy_config=[
ProxyConfig(
server="http://datacenter-proxy.example.com:8080",
username="user",
password="pass",
),
ProxyConfig(
server="http://residential-proxy.example.com:9090",
username="user",
password="pass",
),
],
)
With this setup, each round tries the datacenter proxy first, then the residential proxy. With max_retries=1, worst case is 2 rounds x 2 proxies = 4 attempts.
Fallback Fetch Function
When all browser-based attempts fail, call a custom async function as a last resort. This function receives the URL and must return raw HTML as a string. The returned HTML is processed through the normal pipeline (markdown generation, extraction, etc.).
This is useful when you have access to a scraping API, a pre-fetched cache, or any other source of HTML.
import aiohttp
async def my_scraping_api(url: str) -> str:
"""Fetch HTML via an external scraping API."""
async with aiohttp.ClientSession() as session:
async with session.get(
"https://api.my-scraping-service.com/fetch",
params={"url": url, "format": "html"},
headers={"Authorization": "Bearer MY_TOKEN"},
) as resp:
if resp.status == 200:
return await resp.text()
raise RuntimeError(f"API error: {resp.status}")
config = CrawlerRunConfig(
max_retries=1,
fallback_fetch_function=my_scraping_api,
)
The function can do anything — call an API, read from a database, return cached HTML, or make a simple HTTP request with a different library. Crawl4AI does not care how the HTML is obtained.
Full Escalation (All Features Combined)
This example combines every layer: stealth mode, a list of proxies tried in order, retries, and a final fetch function.
import aiohttp
from crawl4ai import AsyncWebCrawler
from crawl4ai.async_configs import BrowserConfig, CrawlerRunConfig, ProxyConfig
# Last-resort: fetch HTML via an external service
async def external_fetch(url: str) -> str:
async with aiohttp.ClientSession() as session:
async with session.post(
"https://api.my-service.com/scrape",
json={"url": url, "render_js": True},
headers={"Authorization": "Bearer MY_TOKEN"},
) as resp:
return await resp.text()
browser_config = BrowserConfig(
headless=True,
enable_stealth=True,
)
crawl_config = CrawlerRunConfig(
magic=True,
wait_until="load",
max_retries=2,
# Proxies tried in order — cheapest first
proxy_config=[
ProxyConfig(
server="http://datacenter-proxy.example.com:8080",
username="user",
password="pass",
),
ProxyConfig(
server="http://residential-proxy.example.com:9090",
username="user",
password="pass",
),
],
# Last resort — called after all retries and proxies are exhausted
fallback_fetch_function=external_fetch,
)
async with AsyncWebCrawler(config=browser_config) as crawler:
result = await crawler.arun(
url="https://protected-site.com/products",
config=crawl_config,
)
if result.success:
print(f"Got {len(result.markdown.raw_markdown)} chars of markdown")
print(f"Resolved by: {result.crawl_stats['resolved_by']}")
print(f"Attempts: {result.crawl_stats['attempts']}")
else:
print(f"All attempts failed: {result.error_message}")
What happens step by step:
| Round | Attempt | What runs |
|---|---|---|
| 1 | 1 | Datacenter proxy — blocked |
| 1 | 2 | Residential proxy — blocked |
| 2 | 1 | Datacenter proxy — blocked |
| 2 | 2 | Residential proxy — blocked |
| 3 | 1 | Datacenter proxy — blocked |
| 3 | 2 | Residential proxy — blocked |
| - | - | external_fetch(url) called — returns HTML |
That's up to 6 browser attempts + 1 function call before giving up.
Tips
- Start with
max_retries=0and afallback_fetch_functionif you just want a safety net without burning time on retries. - Order proxies cheapest-first — datacenter proxies before residential, residential before premium.
- Combine with stealth mode —
BrowserConfig(enable_stealth=True)andCrawlerRunConfig(magic=True)reduce the chance of being blocked in the first place. wait_until="load"is important for anti-bot sites — the defaultdomcontentloadedcan return before the anti-bot sensor finishes.- Check
crawl_statsto understand what happened — how many attempts, which proxy worked, whether the fallback function was needed.
See Also
- Proxy & Security — Proxy setup, authentication, and rotation
- Undetected Browser — Stealth mode and browser fingerprint evasion
- Session Management — Maintaining sessions across requests
This guide covers proxy configuration and security features in Crawl4AI, including SSL certificate analysis and proxy rotation strategies.
Understanding Proxy Configuration
Crawl4AI recommends configuring proxies per request through CrawlerRunConfig.proxy_config. This gives you precise control, enables rotation strategies, and keeps examples simple enough to copy, paste, and run.
Basic Proxy Setup
Configure proxies that apply to each crawl operation:
import asyncio
from crawl4ai import AsyncWebCrawler, BrowserConfig, CrawlerRunConfig, ProxyConfig
run_config = CrawlerRunConfig(proxy_config=ProxyConfig(server="http://proxy.example.com:8080"))
# run_config = CrawlerRunConfig(proxy_config={"server": "http://proxy.example.com:8080"})
# run_config = CrawlerRunConfig(proxy_config="http://proxy.example.com:8080")
async def main():
browser_config = BrowserConfig()
async with AsyncWebCrawler(config=browser_config) as crawler:
result = await crawler.arun(url="https://example.com", config=run_config)
print(f"Success: {result.success} -> {result.url}")
if __name__ == "__main__":
asyncio.run(main())
!!! note "Why request-level?"
CrawlerRunConfig.proxy_config keeps each request self-contained, so swapping proxies or rotation strategies is just a matter of building a new run configuration.
Supported Proxy Formats
The ProxyConfig.from_string() method supports multiple formats:
from crawl4ai import ProxyConfig
# HTTP proxy with authentication
proxy1 = ProxyConfig.from_string("http://user:pass@192.168.1.1:8080")
# HTTPS proxy
proxy2 = ProxyConfig.from_string("https://proxy.example.com:8080")
# SOCKS5 proxy
proxy3 = ProxyConfig.from_string("socks5://proxy.example.com:1080")
# Simple IP:port format
proxy4 = ProxyConfig.from_string("192.168.1.1:8080")
# IP:port:user:pass format
proxy5 = ProxyConfig.from_string("192.168.1.1:8080:user:pass")
Authenticated Proxies
For proxies requiring authentication:
import asyncio
from crawl4ai import AsyncWebCrawler,BrowserConfig, CrawlerRunConfig, ProxyConfig
run_config = CrawlerRunConfig(
proxy_config=ProxyConfig(
server="http://proxy.example.com:8080",
username="your_username",
password="your_password",
)
)
# Or dictionary style:
# run_config = CrawlerRunConfig(proxy_config={
# "server": "http://proxy.example.com:8080",
# "username": "your_username",
# "password": "your_password",
# })
async def main():
browser_config = BrowserConfig()
async with AsyncWebCrawler(config=browser_config) as crawler:
result = await crawler.arun(url="https://example.com", config=run_config)
print(f"Success: {result.success} -> {result.url}")
if __name__ == "__main__":
asyncio.run(main())
Environment Variable Configuration
Load proxies from environment variables for easy configuration:
import os
from crawl4ai import ProxyConfig, CrawlerRunConfig
# Set environment variable
os.environ["PROXIES"] = "ip1:port1:user1:pass1,ip2:port2:user2:pass2,ip3:port3"
# Load all proxies
proxies = ProxyConfig.from_env()
print(f"Loaded {len(proxies)} proxies")
# Use first proxy
if proxies:
run_config = CrawlerRunConfig(proxy_config=proxies[0])
Rotating Proxies
Crawl4AI supports automatic proxy rotation to distribute requests across multiple proxy servers. Rotation is applied per request using a rotation strategy on CrawlerRunConfig.
Proxy Rotation (recommended)
import asyncio
import re
from crawl4ai import AsyncWebCrawler, BrowserConfig, CrawlerRunConfig, CacheMode, ProxyConfig
from crawl4ai.proxy_strategy import RoundRobinProxyStrategy
async def main():
# Load proxies from environment
proxies = ProxyConfig.from_env()
if not proxies:
print("No proxies found! Set PROXIES environment variable.")
return
# Create rotation strategy
proxy_strategy = RoundRobinProxyStrategy(proxies)
# Configure per-request with proxy rotation
browser_config = BrowserConfig(headless=True, verbose=False)
run_config = CrawlerRunConfig(
cache_mode=CacheMode.BYPASS,
proxy_rotation_strategy=proxy_strategy,
)
async with AsyncWebCrawler(config=browser_config) as crawler:
urls = ["https://httpbin.org/ip"] * (len(proxies) * 2) # Test each proxy twice
print(f"🚀 Testing {len(proxies)} proxies with rotation...")
results = await crawler.arun_many(urls=urls, config=run_config)
for i, result in enumerate(results):
if result.success:
# Extract IP from response
ip_match = re.search(r'(?:[0-9]{1,3}\.){3}[0-9]{1,3}', result.html)
if ip_match:
detected_ip = ip_match.group(0)
proxy_index = i % len(proxies)
expected_ip = proxies[proxy_index].ip
print(f"✅ Request {i+1}: Proxy {proxy_index+1} -> IP {detected_ip}")
if detected_ip == expected_ip:
print(" 🎯 IP matches proxy configuration")
else:
print(f" ⚠️ IP mismatch (expected {expected_ip})")
else:
print(f"❌ Request {i+1}: Could not extract IP from response")
else:
print(f"❌ Request {i+1}: Failed - {result.error_message}")
if __name__ == "__main__":
asyncio.run(main())
SSL Certificate Analysis
Combine proxy usage with SSL certificate inspection for enhanced security analysis. SSL certificate fetching is configured per request via CrawlerRunConfig.
Per-Request SSL Certificate Analysis
import asyncio
from crawl4ai import AsyncWebCrawler, BrowserConfig, CrawlerRunConfig
run_config = CrawlerRunConfig(
proxy_config={
"server": "http://proxy.example.com:8080",
"username": "user",
"password": "pass",
},
fetch_ssl_certificate=True, # Enable SSL certificate analysis for this request
)
async def main():
browser_config = BrowserConfig()
async with AsyncWebCrawler(config=browser_config) as crawler:
result = await crawler.arun(url="https://example.com", config=run_config)
if result.success:
print(f"✅ Crawled via proxy: {result.url}")
# Analyze SSL certificate
if result.ssl_certificate:
cert = result.ssl_certificate
print("🔒 SSL Certificate Info:")
print(f" Issuer: {cert.issuer}")
print(f" Subject: {cert.subject}")
print(f" Valid until: {cert.valid_until}")
print(f" Fingerprint: {cert.fingerprint}")
# Export certificate
cert.to_json("certificate.json")
print("💾 Certificate exported to certificate.json")
else:
print("⚠️ No SSL certificate information available")
if __name__ == "__main__":
asyncio.run(main())
Security Best Practices
1. Proxy Rotation for Anonymity
from crawl4ai import CrawlerRunConfig, ProxyConfig
from crawl4ai.proxy_strategy import RoundRobinProxyStrategy
# Use multiple proxies to avoid IP blocking
proxies = ProxyConfig.from_env("PROXIES")
strategy = RoundRobinProxyStrategy(proxies)
# Configure rotation per request (recommended)
run_config = CrawlerRunConfig(proxy_rotation_strategy=strategy)
# For a fixed proxy across all requests, just reuse the same run_config instance
static_run_config = run_config
2. SSL Certificate Verification
from crawl4ai import CrawlerRunConfig
# Always verify SSL certificates when possible
# Per-request (affects specific requests)
run_config = CrawlerRunConfig(fetch_ssl_certificate=True)
3. Environment Variable Security
# Use environment variables for sensitive proxy credentials
# Avoid hardcoding usernames/passwords in code
export PROXIES="ip1:port1:user1:pass1,ip2:port2:user2:pass2"
4. SOCKS5 for Enhanced Security
from crawl4ai import CrawlerRunConfig
# Prefer SOCKS5 proxies for better protocol support
run_config = CrawlerRunConfig(proxy_config="socks5://proxy.example.com:1080")
Migration from Deprecated proxy Parameter
- "Deprecation Notice"
The legacy
proxyargument onBrowserConfigis deprecated. Configure proxies throughCrawlerRunConfig.proxy_configso each request fully describes its network settings.
# Old (deprecated) approach
# from crawl4ai import BrowserConfig
# browser_config = BrowserConfig(proxy_config="http://proxy.example.com:8080")
# New (preferred) approach
from crawl4ai import CrawlerRunConfig
run_config = CrawlerRunConfig(proxy_config="http://proxy.example.com:8080")
Safe Logging of Proxies
from crawl4ai import ProxyConfig
def safe_proxy_repr(proxy: ProxyConfig):
if getattr(proxy, "username", None):
return f"{proxy.server} (auth: ****)"
return proxy.server
Troubleshooting
Common Issues
-
"Proxy connection failed"
- Verify the proxy server is reachable from your network.
- Double-check authentication credentials.
- Ensure the protocol matches (
http,https, orsocks5).
-
"SSL certificate errors"
- Some proxies break SSL inspection; switch proxies if you see repeated failures.
- Consider temporarily disabling certificate fetching to isolate the issue.
-
"Environment variables not loading"
- Confirm
PROXIES(or your custom env var) is set before running the script. - Check formatting:
ip:port:user:pass,ip:port:user:pass.
- Confirm
-
"Proxy rotation not working"
- Ensure
ProxyConfig.from_env()actually loaded entries (len(proxies) > 0). - Attach
proxy_rotation_strategytoCrawlerRunConfig. - Validate the proxy definitions you pass into the strategy.
- Ensure
See Also
- Anti-Bot Detection & Fallback — Automatic retry with proxy escalation and fallback functions when anti-bot blocking is detected
