高级用法(1/3)
Heads Up: Crawl4AI supports advanced dispatchers for parallel or throttled crawling, providing dynamic rate limiting and memory usage checks. The built-in
arun_many()function uses these dispatchers to handle concurrency efficiently.
1. Introduction
When crawling many URLs:
- Basic: Use
arun()in a loop (simple but less efficient) - Better: Use
arun_many(), which efficiently handles multiple URLs with proper concurrency control - Best: Customize dispatcher behavior for your specific needs (memory management, rate limits, etc.)
Why Dispatchers?
- Adaptive: Memory-based dispatchers can pause or slow down based on system resources
- Rate-limiting: Built-in rate limiting with exponential backoff for 429/503 responses
- Real-time Monitoring: Live dashboard of ongoing tasks, memory usage, and performance
- Flexibility: Choose between memory-adaptive or semaphore-based concurrency
2. Core Components
2.1 Rate Limiter
class RateLimiter:
def __init__(
# Random delay range between requests
base_delay: Tuple[float, float] = (1.0, 3.0),
# Maximum backoff delay
max_delay: float = 60.0,
# Retries before giving up
max_retries: int = 3,
# Status codes triggering backoff
rate_limit_codes: List[int] = [429, 503]
)
Here’s the revised and simplified explanation of the RateLimiter, focusing on constructor parameters and adhering to your markdown style and mkDocs guidelines.
RateLimiter Constructor Parameters
The RateLimiter is a utility that helps manage the pace of requests to avoid overloading servers or getting blocked due to rate limits. It operates internally to delay requests and handle retries but can be configured using its constructor parameters.
Parameters of the RateLimiter constructor:
1. base_delay (Tuple[float, float], default: (1.0, 3.0))
The range for a random delay (in seconds) between consecutive requests to the same domain.
- A random delay is chosen between
base_delay[0]andbase_delay[1]for each request. - This prevents sending requests at a predictable frequency, reducing the chances of triggering rate limits.
Example:
If base_delay = (2.0, 5.0), delays could be randomly chosen as 2.3s, 4.1s, etc.
2. max_delay (float, default: 60.0)
The maximum allowable delay when rate-limiting errors occur.
- When servers return rate-limit responses (e.g., 429 or 503), the delay increases exponentially with jitter.
- The
max_delayensures the delay doesn’t grow unreasonably high, capping it at this value.
Example:
For a max_delay = 30.0, even if backoff calculations suggest a delay of 45s, it will cap at 30s.
3. max_retries (int, default: 3)
The maximum number of retries for a request if rate-limiting errors occur.
- After encountering a rate-limit response, the
RateLimiterretries the request up to this number of times. - If all retries fail, the request is marked as failed, and the process continues.
Example:
If max_retries = 3, the system retries a failed request three times before giving up.
4. rate_limit_codes (List[int], default: [429, 503])
A list of HTTP status codes that trigger the rate-limiting logic.
- These status codes indicate the server is overwhelmed or actively limiting requests.
- You can customize this list to include other codes based on specific server behavior.
Example:
If rate_limit_codes = [429, 503, 504], the crawler will back off on these three error codes.
How to Use the RateLimiter:
Here’s an example of initializing and using a RateLimiter in your project:
from crawl4ai import RateLimiter
# Create a RateLimiter with custom settings
rate_limiter = RateLimiter(
base_delay=(2.0, 4.0), # Random delay between 2-4 seconds
max_delay=30.0, # Cap delay at 30 seconds
max_retries=5, # Retry up to 5 times on rate-limiting errors
rate_limit_codes=[429, 503] # Handle these HTTP status codes
)
# RateLimiter will handle delays and retries internally
# No additional setup is required for its operation
The RateLimiter integrates seamlessly with dispatchers like MemoryAdaptiveDispatcher and SemaphoreDispatcher, ensuring requests are paced correctly without user intervention. Its internal mechanisms manage delays and retries to avoid overwhelming servers while maximizing efficiency.
2.2 Crawler Monitor
The CrawlerMonitor provides real-time visibility into crawling operations:
from crawl4ai import CrawlerMonitor, DisplayMode
monitor = CrawlerMonitor(
# Maximum rows in live display
max_visible_rows=15,
# DETAILED or AGGREGATED view
display_mode=DisplayMode.DETAILED
)
Display Modes:
- DETAILED: Shows individual task status, memory usage, and timing
- AGGREGATED: Displays summary statistics and overall progress
3. Available Dispatchers
3.1 MemoryAdaptiveDispatcher (Default)
Automatically manages concurrency based on system memory usage:
from crawl4ai.async_dispatcher import MemoryAdaptiveDispatcher
dispatcher = MemoryAdaptiveDispatcher(
memory_threshold_percent=90.0, # Pause if memory exceeds this
check_interval=1.0, # How often to check memory
max_session_permit=10, # Maximum concurrent tasks
rate_limiter=RateLimiter( # Optional rate limiting
base_delay=(1.0, 2.0),
max_delay=30.0,
max_retries=2
),
monitor=CrawlerMonitor( # Optional monitoring
max_visible_rows=15,
display_mode=DisplayMode.DETAILED
)
)
Constructor Parameters:
1. memory_threshold_percent (float, default: 90.0)
Specifies the memory usage threshold (as a percentage). If system memory usage exceeds this value, the dispatcher pauses crawling to prevent system overload.
2. check_interval (float, default: 1.0)
The interval (in seconds) at which the dispatcher checks system memory usage.
3. max_session_permit (int, default: 10)
The maximum number of concurrent crawling tasks allowed. This ensures resource limits are respected while maintaining concurrency.
4. memory_wait_timeout (float, default: 600.0)
Optional timeout (in seconds). If memory usage exceeds memory_threshold_percent for longer than this duration, a MemoryError is raised.
5. rate_limiter (RateLimiter, default: None)
Optional rate-limiting logic to avoid server-side blocking (e.g., for handling 429 or 503 errors). See RateLimiter for details.
6. monitor (CrawlerMonitor, default: None)
Optional monitoring for real-time task tracking and performance insights. See CrawlerMonitor for details.
3.2 SemaphoreDispatcher
Provides simple concurrency control with a fixed limit:
from crawl4ai.async_dispatcher import SemaphoreDispatcher
dispatcher = SemaphoreDispatcher(
max_session_permit=20, # Maximum concurrent tasks
rate_limiter=RateLimiter( # Optional rate limiting
base_delay=(0.5, 1.0),
max_delay=10.0
),
monitor=CrawlerMonitor( # Optional monitoring
max_visible_rows=15,
display_mode=DisplayMode.DETAILED
)
)
Constructor Parameters:
1. max_session_permit (int, default: 20)
The maximum number of concurrent crawling tasks allowed, irrespective of semaphore slots.
2. rate_limiter (RateLimiter, default: None)
Optional rate-limiting logic to avoid overwhelming servers. See RateLimiter for details.
3. monitor (CrawlerMonitor, default: None)
Optional monitoring for tracking task progress and resource usage. See CrawlerMonitor for details.
4. Usage Examples
4.1 Batch Processing (Default)
async def crawl_batch():
browser_config = BrowserConfig(headless=True, verbose=False)
run_config = CrawlerRunConfig(
cache_mode=CacheMode.BYPASS,
stream=False # Default: get all results at once
)
dispatcher = MemoryAdaptiveDispatcher(
memory_threshold_percent=70.0,
check_interval=1.0,
max_session_permit=10,
monitor=CrawlerMonitor(
display_mode=DisplayMode.DETAILED
)
)
async with AsyncWebCrawler(config=browser_config) as crawler:
# Get all results at once
results = await crawler.arun_many(
urls=urls,
config=run_config,
dispatcher=dispatcher
)
# Process all results after completion
for result in results:
if result.success:
await process_result(result)
else:
print(f"Failed to crawl {result.url}: {result.error_message}")
Review:
- Purpose: Executes a batch crawl with all URLs processed together after crawling is complete.
- Dispatcher: Uses MemoryAdaptiveDispatcher to manage concurrency and system memory.
- Stream: Disabled (stream=False), so all results are collected at once for post-processing.
- Best Use Case: When you need to analyze results in bulk rather than individually during the crawl.
4.2 Streaming Mode
async def crawl_streaming():
browser_config = BrowserConfig(headless=True, verbose=False)
run_config = CrawlerRunConfig(
cache_mode=CacheMode.BYPASS,
stream=True # Enable streaming mode
)
dispatcher = MemoryAdaptiveDispatcher(
memory_threshold_percent=70.0,
check_interval=1.0,
max_session_permit=10,
monitor=CrawlerMonitor(
display_mode=DisplayMode.DETAILED
)
)
async with AsyncWebCrawler(config=browser_config) as crawler:
# Process results as they become available
async for result in await crawler.arun_many(
urls=urls,
config=run_config,
dispatcher=dispatcher
):
if result.success:
# Process each result immediately
await process_result(result)
else:
print(f"Failed to crawl {result.url}: {result.error_message}")
Review:
- Purpose: Enables streaming to process results as soon as they’re available.
- Dispatcher: Uses MemoryAdaptiveDispatcher for concurrency and memory management.
- Stream: Enabled (stream=True), allowing real-time processing during crawling.
- Best Use Case: When you need to act on results immediately, such as for real-time analytics or progressive data storage.
4.3 Semaphore-based Crawling
async def crawl_with_semaphore(urls):
browser_config = BrowserConfig(headless=True, verbose=False)
run_config = CrawlerRunConfig(cache_mode=CacheMode.BYPASS)
dispatcher = SemaphoreDispatcher(
semaphore_count=5,
rate_limiter=RateLimiter(
base_delay=(0.5, 1.0),
max_delay=10.0
),
monitor=CrawlerMonitor(
max_visible_rows=15,
display_mode=DisplayMode.DETAILED
)
)
async with AsyncWebCrawler(config=browser_config) as crawler:
results = await crawler.arun_many(
urls,
config=run_config,
dispatcher=dispatcher
)
return results
Review:
- Purpose: Uses SemaphoreDispatcher to limit concurrency with a fixed number of slots.
- Dispatcher: Configured with a semaphore to control parallel crawling tasks.
- Rate Limiter: Prevents servers from being overwhelmed by pacing requests.
- Best Use Case: When you want precise control over the number of concurrent requests, independent of system memory.
4.4 Robots.txt Consideration
import asyncio
from crawl4ai import AsyncWebCrawler, CrawlerRunConfig, CacheMode
async def main():
urls = [
"https://example1.com",
"https://example2.com",
"https://example3.com"
]
config = CrawlerRunConfig(
cache_mode=CacheMode.ENABLED,
check_robots_txt=True, # Will respect robots.txt for each URL
semaphore_count=3 # Max concurrent requests
)
async with AsyncWebCrawler() as crawler:
async for result in crawler.arun_many(urls, config=config):
if result.success:
print(f"Successfully crawled {result.url}")
elif result.status_code == 403 and "robots.txt" in result.error_message:
print(f"Skipped {result.url} - blocked by robots.txt")
else:
print(f"Failed to crawl {result.url}: {result.error_message}")
if __name__ == "__main__":
asyncio.run(main())
Review:
- Purpose: Ensures compliance with robots.txt rules for ethical and legal web crawling.
- Configuration: Set check_robots_txt=True to validate each URL against robots.txt before crawling.
- Dispatcher: Handles requests with concurrency limits (semaphore_count=3).
- Best Use Case: When crawling websites that strictly enforce robots.txt policies or for responsible crawling practices.
5. Dispatch Results
Each crawl result includes dispatch information:
@dataclass
class DispatchResult:
task_id: str
memory_usage: float
peak_memory: float
start_time: datetime
end_time: datetime
error_message: str = ""
Access via result.dispatch_result:
for result in results:
if result.success:
dr = result.dispatch_result
print(f"URL: {result.url}")
print(f"Memory: {dr.memory_usage:.1f}MB")
print(f"Duration: {dr.end_time - dr.start_time}")
6. URL-Specific Configurations
When crawling diverse content types, you often need different configurations for different URLs. For example: - PDFs need specialized extraction - Blog pages benefit from content filtering - Dynamic sites need JavaScript execution - API endpoints need JSON parsing
6.1 Basic URL Pattern Matching
from crawl4ai import AsyncWebCrawler, CrawlerRunConfig, MatchMode
from crawl4ai.processors.pdf import PDFContentScrapingStrategy
from crawl4ai.extraction_strategy import JsonCssExtractionStrategy
from crawl4ai.content_filter_strategy import PruningContentFilterLXML
from crawl4ai.markdown_generation_strategy import DefaultMarkdownGenerator
async def crawl_mixed_content():
# Configure different strategies for different content
configs = [
# PDF files - specialized extraction
CrawlerRunConfig(
url_matcher="*.pdf",
scraping_strategy=PDFContentScrapingStrategy()
),
# Blog/article pages - content filtering
CrawlerRunConfig(
url_matcher=["*/blog/*", "*/article/*"],
markdown_generator=DefaultMarkdownGenerator(
content_filter=PruningContentFilterLXML(threshold=0.48)
)
),
# Dynamic pages - JavaScript execution
CrawlerRunConfig(
url_matcher=lambda url: 'github.com' in url,
js_code="window.scrollTo(0, 500);"
),
# API endpoints - JSON extraction
CrawlerRunConfig(
url_matcher=lambda url: 'api' in url or url.endswith('.json'),
# Custome settings for JSON extraction
),
# Default config for everything else
CrawlerRunConfig() # No url_matcher means it matches ALL URLs (fallback)
]
# Mixed URLs
urls = [
"https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf",
"https://blog.python.org/",
"https://github.com/microsoft/playwright",
"https://httpbin.org/json",
"https://example.com/"
]
async with AsyncWebCrawler() as crawler:
results = await crawler.arun_many(
urls=urls,
config=configs # Pass list of configs
)
for result in results:
print(f"{result.url}: {len(result.markdown)} chars")
6.2 Advanced Pattern Matching
Important: A CrawlerRunConfig without url_matcher (or with url_matcher=None) matches ALL URLs. This makes it perfect as a default/fallback configuration.
The url_matcher parameter supports three types of patterns:
Glob Patterns (Strings)
# Simple patterns
"*.pdf" # Any PDF file
"*/api/*" # Any URL with /api/ in path
"https://*.example.com/*" # Subdomain matching
"*://example.com/blog/*" # Any protocol
Custom Functions
# Complex logic with lambdas
lambda url: url.startswith('https://') and 'secure' in url
lambda url: len(url) > 50 and url.count('/') > 5
lambda url: any(domain in url for domain in ['api.', 'data.', 'feed.'])
Mixed Lists with AND/OR Logic
# Combine multiple conditions
CrawlerRunConfig(
url_matcher=[
"https://*", # Must be HTTPS
lambda url: 'internal' in url, # Must contain 'internal'
lambda url: not url.endswith('.pdf') # Must not be PDF
],
match_mode=MatchMode.AND # ALL conditions must match
)
6.3 Practical Example: News Site Crawler
async def crawl_news_site():
dispatcher = MemoryAdaptiveDispatcher(
memory_threshold_percent=70.0,
rate_limiter=RateLimiter(base_delay=(1.0, 2.0))
)
configs = [
# Homepage - light extraction
CrawlerRunConfig(
url_matcher=lambda url: url.rstrip('/') == 'https://news.ycombinator.com',
css_selector="nav, .headline",
extraction_strategy=None
),
# Article pages - full extraction
CrawlerRunConfig(
url_matcher="*/article/*",
extraction_strategy=CosineStrategy(
semantic_filter="article content",
word_count_threshold=100
),
screenshot=True,
excluded_tags=["nav", "aside", "footer"]
),
# Author pages - metadata focus
CrawlerRunConfig(
url_matcher="*/author/*",
extraction_strategy=JsonCssExtractionStrategy({
"name": "h1.author-name",
"bio": ".author-bio",
"articles": "article.post-card h2"
})
),
# Everything else
CrawlerRunConfig()
]
async with AsyncWebCrawler() as crawler:
results = await crawler.arun_many(
urls=news_urls,
config=configs,
dispatcher=dispatcher
)
6.4 Best Practices
- Order Matters: Configs are evaluated in order - put specific patterns before general ones
- Default Config Behavior:
- A config without
url_matchermatches ALL URLs - Always include a default config as the last item if you want to handle all URLs
- Without a default config, unmatched URLs will fail with "No matching configuration found"
- Test Your Patterns: Use the config's
is_match()method to test patterns:
config = CrawlerRunConfig(url_matcher="*.pdf")
print(config.is_match("https://example.com/doc.pdf")) # True
default_config = CrawlerRunConfig() # No url_matcher
print(default_config.is_match("https://any-url.com")) # True - matches everything!
- Optimize for Performance:
- Disable JS for static content
- Skip screenshots for data APIs
- Use appropriate extraction strategies
7. Summary
1. Two Dispatcher Types:
- MemoryAdaptiveDispatcher (default): Dynamic concurrency based on memory
- SemaphoreDispatcher: Fixed concurrency limit
2. Optional Components:
- RateLimiter: Smart request pacing and backoff
- CrawlerMonitor: Real-time progress visualization
3. Key Benefits:
- Automatic memory management
- Built-in rate limiting
- Live progress monitoring
- Flexible concurrency control
Choose the dispatcher that best fits your needs:
- MemoryAdaptiveDispatcher: For large crawls or limited resources
- SemaphoreDispatcher: For simple, fixed-concurrency scenarios
Crawl4AI empowers you to navigate and interact with the web using your authentic digital identity, ensuring you’re recognized as a human and not mistaken for a bot. This tutorial covers:
1. Managed Browsers – The recommended approach for persistent profiles and identity-based crawling. 2. Magic Mode – A simplified fallback solution for quick automation without persistent identity.
1. Managed Browsers: Your Digital Identity Solution
Managed Browsers let developers create and use persistent browser profiles. These profiles store local storage, cookies, and other session data, letting you browse as your real self—complete with logins, preferences, and cookies.
Key Benefits
- Authentic Browsing Experience: Retain session data and browser fingerprints as though you’re a normal user.
- Effortless Configuration: Once you log in or solve CAPTCHAs in your chosen data directory, you can re-run crawls without repeating those steps.
- Empowered Data Access: If you can see the data in your own browser, you can automate its retrieval with your genuine identity.
Below is a partial update to your Managed Browsers tutorial, specifically the section about creating a user-data directory using Playwright’s Chromium binary rather than a system-wide Chrome/Edge. We’ll show how to locate that binary and launch it with a --user-data-dir argument to set up your profile. You can then point BrowserConfig.user_data_dir to that folder for subsequent crawls.
Creating a User Data Directory (Command-Line Approach via Playwright)
If you installed Crawl4AI (which installs Playwright under the hood), you already have a Playwright-managed Chromium on your system. Follow these steps to launch that Chromium from your command line, specifying a custom data directory:
1. Find the Playwright Chromium binary:
- On most systems, installed browsers go under a ~/.cache/ms-playwright/ folder or similar path.
- To see an overview of installed browsers, run:
python -m playwright install --dry-run
or
playwright install --dry-run
(depending on your environment). This shows where Playwright keeps Chromium.
- For instance, you might see a path like:
~/.cache/ms-playwright/chromium-1234/chrome-linux/chrome
on Linux, or a corresponding folder on macOS/Windows.
2. Launch the Playwright Chromium binary with a custom user-data directory:
# Linux example
~/.cache/ms-playwright/chromium-1234/chrome-linux/chrome \
--user-data-dir=/home/<you>/my_chrome_profile
# macOS example (Playwright’s internal binary)
~/Library/Caches/ms-playwright/chromium-1234/chrome-mac/Chromium.app/Contents/MacOS/Chromium \
--user-data-dir=/Users/<you>/my_chrome_profile
# Windows example (PowerShell/cmd)
"C:\Users\<you>\AppData\Local\ms-playwright\chromium-1234\chrome-win\chrome.exe" ^
--user-data-dir="C:\Users\<you>\my_chrome_profile"
Replace the path with the actual subfolder indicated in your ms-playwright cache structure.
- This opens a fresh Chromium with your new or existing data folder.
- Log into any sites or configure your browser the way you want.
- Close when done—your profile data is saved in that folder.
3. Use that folder in BrowserConfig.user_data_dir:
from crawl4ai import AsyncWebCrawler, BrowserConfig, CrawlerRunConfig
browser_config = BrowserConfig(
headless=True,
use_managed_browser=True,
user_data_dir="/home/<you>/my_chrome_profile",
browser_type="chromium"
)
- Next time you run your code, it reuses that folder—preserving your session data, cookies, local storage, etc.
Creating a Profile Using the Crawl4AI CLI (Easiest)
If you prefer a guided, interactive setup, use the built-in CLI to create and manage persistent browser profiles.
1.⠀Launch the profile manager:
crwl profiles
2.⠀Choose "Create new profile" and enter a profile name. A Chromium window opens so you can log in to sites and configure settings. When finished, return to the terminal and press q to save the profile.
3.⠀Profiles are saved under ~/.crawl4ai/profiles/<profile_name> (for example: /home/<you>/.crawl4ai/profiles/test_profile_1) along with a storage_state.json for cookies and session data.
4.⠀Optionally, choose "List profiles" in the CLI to view available profiles and their paths.
5.⠀Use the saved path with BrowserConfig.user_data_dir:
from crawl4ai import AsyncWebCrawler, BrowserConfig
profile_path = "/home/<you>/.crawl4ai/profiles/test_profile_1"
browser_config = BrowserConfig(
headless=True,
use_managed_browser=True,
user_data_dir=profile_path,
browser_type="chromium",
)
async with AsyncWebCrawler(config=browser_config) as crawler:
result = await crawler.arun(url="https://example.com/private")
The CLI also supports listing and deleting profiles, and even testing a crawl directly from the menu.
3. Using Managed Browsers in Crawl4AI
Once you have a data directory with your session data, pass it to BrowserConfig:
import asyncio
from crawl4ai import AsyncWebCrawler, BrowserConfig, CrawlerRunConfig
async def main():
# 1) Reference your persistent data directory
browser_config = BrowserConfig(
headless=True, # 'True' for automated runs
verbose=True,
use_managed_browser=True, # Enables persistent browser strategy
browser_type="chromium",
user_data_dir="/path/to/my-chrome-profile"
)
# 2) Standard crawl config
crawl_config = CrawlerRunConfig(
wait_for="css:.logged-in-content"
)
async with AsyncWebCrawler(config=browser_config) as crawler:
result = await crawler.arun(url="https://example.com/private", config=crawl_config)
if result.success:
print("Successfully accessed private data with your identity!")
else:
print("Error:", result.error_message)
if __name__ == "__main__":
asyncio.run(main())
Workflow
1. Login externally (via CLI or your normal Chrome with --user-data-dir=...).
2. Close that browser.
3. Use the same folder in user_data_dir= in Crawl4AI.
4. Crawl – The site sees your identity as if you’re the same user who just logged in.
4. Magic Mode: Simplified Automation
If you don’t need a persistent profile or identity-based approach, Magic Mode offers a quick way to simulate human-like browsing without storing long-term data.
from crawl4ai import AsyncWebCrawler, CrawlerRunConfig
async with AsyncWebCrawler() as crawler:
result = await crawler.arun(
url="https://example.com",
config=CrawlerRunConfig(
magic=True, # Simplifies a lot of interaction
remove_overlay_elements=True,
page_timeout=60000
)
)
Magic Mode:
- Simulates a user-like experience
- Randomizes user agent & navigator
- Randomizes interactions & timings
- Masks automation signals
- Attempts pop-up handling
But it’s no substitute for true user-based sessions if you want a fully legitimate identity-based solution.
5. Comparing Managed Browsers vs. Magic Mode
| Feature | Managed Browsers | Magic Mode |
|---|---|---|
| Session Persistence | Full localStorage/cookies retained in user_data_dir | No persistent data (fresh each run) |
| Genuine Identity | Real user profile with full rights & preferences | Emulated user-like patterns, but no actual identity |
| Complex Sites | Best for login-gated sites or heavy config | Simple tasks, minimal login or config needed |
| Setup | External creation of user_data_dir, then use in Crawl4AI | Single-line approach (magic=True) |
| Reliability | Extremely consistent (same data across runs) | Good for smaller tasks, can be less stable |
6. Using the BrowserProfiler Class
Crawl4AI provides a dedicated BrowserProfiler class for managing browser profiles, making it easy to create, list, and delete profiles for identity-based browsing.
Creating and Managing Profiles with BrowserProfiler
The BrowserProfiler class offers a comprehensive API for browser profile management:
import asyncio
from crawl4ai import BrowserProfiler
async def manage_profiles():
# Create a profiler instance
profiler = BrowserProfiler()
# Create a profile interactively - opens a browser window
profile_path = await profiler.create_profile(
profile_name="my-login-profile" # Optional: name your profile
)
print(f"Profile saved at: {profile_path}")
# List all available profiles
profiles = profiler.list_profiles()
for profile in profiles:
print(f"Profile: {profile['name']}")
print(f" Path: {profile['path']}")
print(f" Created: {profile['created']}")
print(f" Browser type: {profile['type']}")
# Get a specific profile path by name
specific_profile = profiler.get_profile_path("my-login-profile")
# Delete a profile when no longer needed
success = profiler.delete_profile("old-profile-name")
asyncio.run(manage_profiles())
How profile creation works:
1. A browser window opens for you to interact with
2. You log in to websites, set preferences, etc.
3. When you're done, press 'q' in the terminal to close the browser
4. The profile is saved in the Crawl4AI profiles directory
5. You can use the returned path with BrowserConfig.user_data_dir
Interactive Profile Management
The BrowserProfiler also offers an interactive management console that guides you through profile creation, listing, and deletion:
import asyncio
from crawl4ai import BrowserProfiler, AsyncWebCrawler, BrowserConfig
# Define a function to use a profile for crawling
async def crawl_with_profile(profile_path, url):
browser_config = BrowserConfig(
headless=True,
use_managed_browser=True,
user_data_dir=profile_path
)
async with AsyncWebCrawler(config=browser_config) as crawler:
result = await crawler.arun(url)
return result
async def main():
# Create a profiler instance
profiler = BrowserProfiler()
# Launch the interactive profile manager
# Passing the crawl function as a callback adds a "crawl with profile" option
await profiler.interactive_manager(crawl_callback=crawl_with_profile)
asyncio.run(main())
Legacy Methods
For backward compatibility, the previous methods on ManagedBrowser are still available, but they delegate to the new BrowserProfiler class:
from crawl4ai.browser_manager import ManagedBrowser
# These methods still work but use BrowserProfiler internally
profiles = ManagedBrowser.list_profiles()
Complete Example
See the full example in docs/examples/identity_based_browsing.py for a complete demonstration of creating and using profiles for authenticated browsing using the new BrowserProfiler class.
7. Locale, Timezone, and Geolocation Control
In addition to using persistent profiles, Crawl4AI supports customizing your browser's locale, timezone, and geolocation settings. These features enhance your identity-based browsing experience by allowing you to control how websites perceive your location and regional settings.
Setting Locale and Timezone
You can set the browser's locale and timezone through CrawlerRunConfig:
from crawl4ai import AsyncWebCrawler, CrawlerRunConfig
async with AsyncWebCrawler() as crawler:
result = await crawler.arun(
url="https://example.com",
config=CrawlerRunConfig(
# Set browser locale (language and region formatting)
locale="fr-FR", # French (France)
# Set browser timezone
timezone_id="Europe/Paris",
# Other normal options...
magic=True,
page_timeout=60000
)
)
How it works:
- locale affects language preferences, date formats, number formats, etc.
- timezone_id affects JavaScript's Date object and time-related functionality
- These settings are applied when creating the browser context and maintained throughout the session
Configuring Geolocation
Control the GPS coordinates reported by the browser's geolocation API:
from crawl4ai import AsyncWebCrawler, CrawlerRunConfig, GeolocationConfig
async with AsyncWebCrawler() as crawler:
result = await crawler.arun(
url="https://maps.google.com", # Or any location-aware site
config=CrawlerRunConfig(
# Configure precise GPS coordinates
geolocation=GeolocationConfig(
latitude=48.8566, # Paris coordinates
longitude=2.3522,
accuracy=100 # Accuracy in meters (optional)
),
# This site will see you as being in Paris
page_timeout=60000
)
)
Important notes:
- When geolocation is specified, the browser is automatically granted permission to access location
- Websites using the Geolocation API will receive the exact coordinates you specify
- This affects map services, store locators, delivery services, etc.
- Combined with the appropriate locale and timezone_id, you can create a fully consistent location profile
Combining with Managed Browsers
These settings work perfectly with managed browsers for a complete identity solution:
from crawl4ai import (
AsyncWebCrawler, BrowserConfig, CrawlerRunConfig,
GeolocationConfig
)
browser_config = BrowserConfig(
use_managed_browser=True,
user_data_dir="/path/to/my-profile",
browser_type="chromium"
)
crawl_config = CrawlerRunConfig(
# Location settings
locale="es-MX", # Spanish (Mexico)
timezone_id="America/Mexico_City",
geolocation=GeolocationConfig(
latitude=19.4326, # Mexico City
longitude=-99.1332
)
)
async with AsyncWebCrawler(config=browser_config) as crawler:
result = await crawler.arun(url="https://example.com", config=crawl_config)
Combining persistent profiles with precise geolocation and region settings gives you complete control over your digital identity.
8. Summary
- Create your user-data directory either:
- By launching Chrome/Chromium externally with
--user-data-dir=/some/path - Or by using the built-in
BrowserProfiler.create_profile()method - Or through the interactive interface with
profiler.interactive_manager() - Log in or configure sites as needed, then close the browser
- Reference that folder in
BrowserConfig(user_data_dir="...")+use_managed_browser=True - Customize identity aspects with
locale,timezone_id, andgeolocation - List and reuse profiles with
BrowserProfiler.list_profiles() - Manage your profiles with the dedicated
BrowserProfilerclass - Enjoy persistent sessions that reflect your real identity
- If you only need quick, ephemeral automation, Magic Mode might suffice
Recommended: Always prefer a Managed Browser for robust, identity-based crawling and simpler interactions with complex sites. Use Magic Mode for quick tasks or prototypes where persistent data is unnecessary.
With these approaches, you preserve your authentic browsing environment, ensuring the site sees you exactly as a normal user—no repeated logins or wasted time.
