迁移与 API 参考(2/3)
The CrawlResult class encapsulates everything returned after a single crawl operation. It provides the raw or processed content, details on links and media, plus optional metadata (like screenshots, PDFs, or extracted JSON).
Location: crawl4ai/crawler/models.py (for reference)
class CrawlResult(BaseModel):
url: str
html: str
success: bool
cleaned_html: Optional[str] = None
fit_html: Optional[str] = None # Preprocessed HTML optimized for extraction
media: Dict[str, List[Dict]] = {}
links: Dict[str, List[Dict]] = {}
downloaded_files: Optional[List[str]] = None
screenshot: Optional[str] = None
pdf : Optional[bytes] = None
mhtml: Optional[str] = None
markdown: Optional[Union[str, MarkdownGenerationResult]] = None
extracted_content: Optional[str] = None
metadata: Optional[dict] = None
error_message: Optional[str] = None
session_id: Optional[str] = None
response_headers: Optional[dict] = None
status_code: Optional[int] = None
redirected_status_code: Optional[int] = None
ssl_certificate: Optional[SSLCertificate] = None
dispatch_result: Optional[DispatchResult] = None
...
Below is a field-by-field explanation and possible usage patterns.
1. Basic Crawl Info
1.1 url (str)
What: The final crawled URL (after any redirects). Usage:
print(result.url) # e.g., "https://example.com/"
1.2 success (bool)
What: True if the crawl pipeline ended without major errors; False otherwise.
Usage:
if not result.success:
print(f"Crawl failed: {result.error_message}")
1.3 status_code (Optional[int])
What: The page's HTTP status code (e.g., 200, 404). When the page was reached via redirect, this is the status code of the first response in the redirect chain (e.g., 301 or 302). Usage:
if result.status_code == 404:
print("Page not found!")
1.4 redirected_status_code (Optional[int])
What: The HTTP status code of the final redirect destination. For a 302→200 redirect, status_code is 302 and redirected_status_code is 200. None for non-HTTP requests (raw HTML, local files).
Usage:
if result.status_code in (301, 302) and result.redirected_status_code == 200:
print(f"Redirected to {result.redirected_url} (OK)")
1.5 error_message (Optional[str])
What: If success=False, a textual description of the failure.
Usage:
if not result.success:
print("Error:", result.error_message)
1.5 session_id (Optional[str])
What: The ID used for reusing a browser context across multiple calls. Usage:
# If you used session_id="login_session" in CrawlerRunConfig, see it here:
print("Session:", result.session_id)
1.6 response_headers (Optional[dict])
What: Final HTTP response headers. Usage:
if result.response_headers:
print("Server:", result.response_headers.get("Server", "Unknown"))
1.7 ssl_certificate (Optional[SSLCertificate])
What: If fetch_ssl_certificate=True in your CrawlerRunConfig, result.ssl_certificate contains a SSLCertificate object describing the site's certificate. You can export the cert in multiple formats (PEM/DER/JSON) or access its properties like issuer,
subject, valid_from, valid_until, etc.
Usage:
if result.ssl_certificate:
print("Issuer:", result.ssl_certificate.issuer)
2. Raw / Cleaned Content
2.1 html (str)
What: The original unmodified HTML from the final page load. Usage:
# Possibly large
print(len(result.html))
2.2 cleaned_html (Optional[str])
What: A sanitized HTML version—scripts, styles, or excluded tags are removed based on your CrawlerRunConfig.
Usage:
print(result.cleaned_html[:500]) # Show a snippet
3. Markdown Fields
3.1 The Markdown Generation Approach
Crawl4AI can convert HTML→Markdown, optionally including:
- Raw markdown
- Links as citations (with a references section)
- Fit markdown if a content filter is used (like Pruning or BM25)
MarkdownGenerationResult includes:
- raw_markdown (str): The full HTML→Markdown conversion.
- markdown_with_citations (str): Same markdown, but with link references as academic-style citations.
- references_markdown (str): The reference list or footnotes at the end.
- fit_markdown (Optional[str]): If content filtering (Pruning/BM25) was applied, the filtered "fit" text.
- fit_html (Optional[str]): The HTML that led to fit_markdown.
Usage:
if result.markdown:
md_res = result.markdown
print("Raw MD:", md_res.raw_markdown[:300])
print("Citations MD:", md_res.markdown_with_citations[:300])
print("References:", md_res.references_markdown)
if md_res.fit_markdown:
print("Pruned text:", md_res.fit_markdown[:300])
3.2 markdown (Optional[Union[str, MarkdownGenerationResult]])
What: Holds the MarkdownGenerationResult.
Usage:
print(result.markdown.raw_markdown[:200])
print(result.markdown.fit_markdown)
print(result.markdown.fit_html)
Important: "Fit" content (in fit_markdown/fit_html) exists in result.markdown, only if you used a filter (like PruningContentFilterLXML or BM25ContentFilter) within a MarkdownGenerationStrategy.
4. Media & Links
4.1 media (Dict[str, List[Dict]])
What: Contains info about discovered images, videos, or audio. Typically keys: "images", "videos", "audios".
Common Fields in each item:
src(str): Media URLaltortitle(str): Descriptive textscore(float): Relevance score if the crawler's heuristic found it "important"descordescription(Optional[str]): Additional context extracted from surrounding text
Usage:
images = result.media.get("images", [])
for img in images:
if img.get("score", 0) > 5:
print("High-value image:", img["src"])
4.2 links (Dict[str, List[Dict]])
What: Holds internal and external link data. Usually two keys: "internal" and "external".
Common Fields:
href(str): The link targettext(str): Link texttitle(str): Title attributecontext(str): Surrounding text snippetdomain(str): If external, the domain
Usage:
for link in result.links["internal"]:
print(f"Internal link to {link['href']} with text {link['text']}")
5. Additional Fields
5.1 extracted_content (Optional[str])
What: If you used extraction_strategy (CSS, LLM, etc.), the structured output (JSON).
Usage:
if result.extracted_content:
data = json.loads(result.extracted_content)
print(data)
5.2 downloaded_files (Optional[List[str]])
What: If accept_downloads=True in your BrowserConfig + downloads_path, lists local file paths for downloaded items.
Usage:
if result.downloaded_files:
for file_path in result.downloaded_files:
print("Downloaded:", file_path)
5.3 screenshot (Optional[str])
What: Base64-encoded screenshot if screenshot=True in CrawlerRunConfig.
Usage:
import base64
if result.screenshot:
with open("page.png", "wb") as f:
f.write(base64.b64decode(result.screenshot))
5.4 pdf (Optional[bytes])
What: Raw PDF bytes if pdf=True in CrawlerRunConfig.
Usage:
if result.pdf:
with open("page.pdf", "wb") as f:
f.write(result.pdf)
5.5 mhtml (Optional[str])
What: MHTML snapshot of the page if capture_mhtml=True in CrawlerRunConfig. MHTML (MIME HTML) format preserves the entire web page with all its resources (CSS, images, scripts, etc.) in a single file.
Usage:
if result.mhtml:
with open("page.mhtml", "w", encoding="utf-8") as f:
f.write(result.mhtml)
5.6 metadata (Optional[dict])
What: Page-level metadata if discovered (title, description, OG data, etc.). Usage:
if result.metadata:
print("Title:", result.metadata.get("title"))
print("Author:", result.metadata.get("author"))
6. dispatch_result (optional)
A DispatchResult object providing additional concurrency and resource usage information when crawling URLs in parallel (e.g., via arun_many() with custom dispatchers). It contains:
task_id: A unique identifier for the parallel task.memory_usage(float): The memory (in MB) used at the time of completion.peak_memory(float): The peak memory usage (in MB) recorded during the task's execution.start_time/end_time(datetime): Time range for this crawling task.error_message(str): Any dispatcher- or concurrency-related error encountered.
# Example usage:
for result in results:
if result.success and result.dispatch_result:
dr = result.dispatch_result
print(f"URL: {result.url}, Task ID: {dr.task_id}")
print(f"Memory: {dr.memory_usage:.1f} MB (Peak: {dr.peak_memory:.1f} MB)")
print(f"Duration: {dr.end_time - dr.start_time}")
Note: This field is typically populated when using
arun_many(...)alongside a dispatcher (e.g.,MemoryAdaptiveDispatcherorSemaphoreDispatcher). If no concurrency or dispatcher is used,dispatch_resultmay remainNone.
7. Network Requests & Console Messages
When you enable network and console message capturing in CrawlerRunConfig using capture_network_requests=True and capture_console_messages=True, the CrawlResult will include these fields:
7.1 network_requests (Optional[List[Dict[str, Any]]])
What: A list of dictionaries containing information about all network requests, responses, and failures captured during the crawl.
Structure:
- Each item has an event_type field that can be "request", "response", or "request_failed".
- Request events include url, method, headers, post_data, resource_type, and is_navigation_request.
- Response events include url, status, status_text, headers, and request_timing.
- Failed request events include url, method, resource_type, and failure_text.
- All events include a timestamp field.
Usage:
if result.network_requests:
# Count different types of events
requests = [r for r in result.network_requests if r.get("event_type") == "request"]
responses = [r for r in result.network_requests if r.get("event_type") == "response"]
failures = [r for r in result.network_requests if r.get("event_type") == "request_failed"]
print(f"Captured {len(requests)} requests, {len(responses)} responses, and {len(failures)} failures")
# Analyze API calls
api_calls = [r for r in requests if "api" in r.get("url", "")]
# Identify failed resources
for failure in failures:
print(f"Failed to load: {failure.get('url')} - {failure.get('failure_text')}")
7.2 console_messages (Optional[List[Dict[str, Any]]])
What: A list of dictionaries containing all browser console messages captured during the crawl.
Structure:
- Each item has a type field indicating the message type (e.g., "log", "error", "warning", etc.).
- The text field contains the actual message text.
- Some messages include location information (URL, line, column).
- All messages include a timestamp field.
Usage:
if result.console_messages:
# Count messages by type
message_types = {}
for msg in result.console_messages:
msg_type = msg.get("type", "unknown")
message_types[msg_type] = message_types.get(msg_type, 0) + 1
print(f"Message type counts: {message_types}")
# Display errors (which are usually most important)
for msg in result.console_messages:
if msg.get("type") == "error":
print(f"Error: {msg.get('text')}")
These fields provide deep visibility into the page's network activity and browser console, which is invaluable for debugging, security analysis, and understanding complex web applications.
For more details on network and console capturing, see the Network & Console Capture documentation.
8. Example: Accessing Everything
async def handle_result(result: CrawlResult):
if not result.success:
print("Crawl error:", result.error_message)
return
# Basic info
print("Crawled URL:", result.url)
print("Status code:", result.status_code)
# HTML
print("Original HTML size:", len(result.html))
print("Cleaned HTML size:", len(result.cleaned_html or ""))
# Markdown output
if result.markdown:
print("Raw Markdown:", result.markdown.raw_markdown[:300])
print("Citations Markdown:", result.markdown.markdown_with_citations[:300])
if result.markdown.fit_markdown:
print("Fit Markdown:", result.markdown.fit_markdown[:200])
# Media & Links
if "images" in result.media:
print("Image count:", len(result.media["images"]))
if "internal" in result.links:
print("Internal link count:", len(result.links["internal"]))
# Extraction strategy result
if result.extracted_content:
print("Structured data:", result.extracted_content)
# Screenshot/PDF/MHTML
if result.screenshot:
print("Screenshot length:", len(result.screenshot))
if result.pdf:
print("PDF bytes length:", len(result.pdf))
if result.mhtml:
print("MHTML length:", len(result.mhtml))
# Network and console capturing
if result.network_requests:
print(f"Network requests captured: {len(result.network_requests)}")
# Analyze request types
req_types = {}
for req in result.network_requests:
if "resource_type" in req:
req_types[req["resource_type"]] = req_types.get(req["resource_type"], 0) + 1
print(f"Resource types: {req_types}")
if result.console_messages:
print(f"Console messages captured: {len(result.console_messages)}")
# Count by message type
msg_types = {}
for msg in result.console_messages:
msg_types[msg.get("type", "unknown")] = msg_types.get(msg.get("type", "unknown"), 0) + 1
print(f"Message types: {msg_types}")
9. Key Points & Future
1. Deprecated legacy properties of CrawlResult
- markdown_v2 - Removed in v0.5 and now raises AttributeError. Use result.markdown instead.
- fit_markdown and fit_html - No longer top-level properties in v0.5. Use result.markdown.fit_markdown and result.markdown.fit_html.
2. Fit Content
- fit_markdown and fit_html appear in MarkdownGenerationResult, only if you used a content filter (like PruningContentFilterLXML or BM25ContentFilter) inside your MarkdownGenerationStrategy or set them directly.
- If no filter is used, they remain None.
3. References & Citations
- If you enable link citations in your DefaultMarkdownGenerator (options={"citations": True}), you’ll see markdown_with_citations plus a references_markdown block. This helps large language models or academic-like referencing.
4. Links & Media
- links["internal"] and links["external"] group discovered anchors by domain.
- media["images"] / ["videos"] / ["audios"] store extracted media elements with optional scoring or context.
5. Error Cases
- If success=False, check error_message (e.g., timeouts, invalid URLs).
- status_code might be None if we failed before an HTTP response.
Use CrawlResult to glean all final outputs and feed them into your data pipelines, AI models, or archives. With the synergy of a properly configured BrowserConfig and CrawlerRunConfig, the crawler can produce robust, structured results here in CrawlResult.
This documentation covers the API reference for extraction and chunking strategies in Crawl4AI.
Extraction Strategies
All extraction strategies inherit from the base ExtractionStrategy class and implement two key methods:
- extract(url: str, html: str) -> List[Dict[str, Any]]
- run(url: str, sections: List[str]) -> List[Dict[str, Any]]
LLMExtractionStrategy
Used for extracting structured data using Language Models.
LLMExtractionStrategy(
# Required Parameters
provider: str = DEFAULT_PROVIDER, # LLM provider (e.g., "ollama/llama2")
api_token: Optional[str] = None, # API token
# Extraction Configuration
instruction: str = None, # Custom extraction instruction
schema: Dict = None, # Pydantic model schema for structured data
extraction_type: str = "block", # "block" or "schema"
# Chunking Parameters
chunk_token_threshold: int = 4000, # Maximum tokens per chunk
overlap_rate: float = 0.1, # Overlap between chunks
word_token_rate: float = 0.75, # Word to token conversion rate
apply_chunking: bool = True, # Enable/disable chunking
# API Configuration
base_url: str = None, # Base URL for API
extra_args: Dict = {}, # Additional provider arguments
verbose: bool = False # Enable verbose logging
)
RegexExtractionStrategy
Used for fast pattern-based extraction of common entities using regular expressions.
RegexExtractionStrategy(
# Pattern Configuration
pattern: IntFlag = RegexExtractionStrategy.Nothing, # Bit flags of built-in patterns to use
custom: Optional[Dict[str, str]] = None, # Custom pattern dictionary {label: regex}
# Input Format
input_format: str = "fit_html", # "html", "markdown", "text" or "fit_html"
)
# Built-in Patterns as Bit Flags
RegexExtractionStrategy.Email # Email addresses
RegexExtractionStrategy.PhoneIntl # International phone numbers
RegexExtractionStrategy.PhoneUS # US-format phone numbers
RegexExtractionStrategy.Url # HTTP/HTTPS URLs
RegexExtractionStrategy.IPv4 # IPv4 addresses
RegexExtractionStrategy.IPv6 # IPv6 addresses
RegexExtractionStrategy.Uuid # UUIDs
RegexExtractionStrategy.Currency # Currency values (USD, EUR, etc)
RegexExtractionStrategy.Percentage # Percentage values
RegexExtractionStrategy.Number # Numeric values
RegexExtractionStrategy.DateIso # ISO format dates
RegexExtractionStrategy.DateUS # US format dates
RegexExtractionStrategy.Time24h # 24-hour format times
RegexExtractionStrategy.PostalUS # US postal codes
RegexExtractionStrategy.PostalUK # UK postal codes
RegexExtractionStrategy.HexColor # HTML hex color codes
RegexExtractionStrategy.TwitterHandle # Twitter handles
RegexExtractionStrategy.Hashtag # Hashtags
RegexExtractionStrategy.MacAddr # MAC addresses
RegexExtractionStrategy.Iban # International bank account numbers
RegexExtractionStrategy.CreditCard # Credit card numbers
RegexExtractionStrategy.All # All available patterns
CosineStrategy
Used for content similarity-based extraction and clustering.
CosineStrategy(
# Content Filtering
semantic_filter: str = None, # Topic/keyword filter
word_count_threshold: int = 10, # Minimum words per cluster
sim_threshold: float = 0.3, # Similarity threshold
# Clustering Parameters
max_dist: float = 0.2, # Maximum cluster distance
linkage_method: str = 'ward', # Clustering method
top_k: int = 3, # Top clusters to return
# Model Configuration
model_name: str = 'sentence-transformers/all-MiniLM-L6-v2', # Embedding model
verbose: bool = False # Enable verbose logging
)
JsonCssExtractionStrategy
Used for CSS selector-based structured data extraction.
JsonCssExtractionStrategy(
schema: Dict[str, Any], # Extraction schema
verbose: bool = False # Enable verbose logging
)
# Schema Structure
schema = {
"name": str, # Schema name
"baseSelector": str, # Base CSS selector
"fields": [ # List of fields to extract
{
"name": str, # Field name
"selector": str, # CSS selector
"type": str, # Field type: "text", "attribute", "html", "regex"
"attribute": str, # For type="attribute"
"pattern": str, # For type="regex"
"transform": str, # Optional: "lowercase", "uppercase", "strip"
"default": Any, # Default value if extraction fails
"source": str, # Optional: navigate to sibling first, e.g. "+ tr"
}
]
}
Chunking Strategies
All chunking strategies inherit from ChunkingStrategy and implement the chunk(text: str) -> list method.
RegexChunking
Splits text based on regex patterns.
RegexChunking(
patterns: List[str] = None # Regex patterns for splitting
# Default: [r'\n\n']
)
SlidingWindowChunking
Creates overlapping chunks with a sliding window approach.
SlidingWindowChunking(
window_size: int = 100, # Window size in words
step: int = 50 # Step size between windows
)
OverlappingWindowChunking
Creates chunks with specified overlap.
OverlappingWindowChunking(
window_size: int = 1000, # Chunk size in words
overlap: int = 100 # Overlap size in words
)
Usage Examples
LLM Extraction
from pydantic import BaseModel
from crawl4ai import LLMExtractionStrategy
from crawl4ai import LLMConfig
# Define schema
class Article(BaseModel):
title: str
content: str
author: str
# Create strategy
strategy = LLMExtractionStrategy(
llm_config = LLMConfig(provider="ollama/llama2"),
schema=Article.schema(),
instruction="Extract article details"
)
# Use with crawler
result = await crawler.arun(
url="https://example.com/article",
extraction_strategy=strategy
)
# Access extracted data
data = json.loads(result.extracted_content)
Regex Extraction
import json
from crawl4ai import AsyncWebCrawler, CrawlerRunConfig, RegexExtractionStrategy
# Method 1: Use built-in patterns
strategy = RegexExtractionStrategy(
pattern = RegexExtractionStrategy.Email | RegexExtractionStrategy.Url
)
# Method 2: Use custom patterns
price_pattern = {"usd_price": r"\$\s?\d{1,3}(?:,\d{3})*(?:\.\d{2})?"}
strategy = RegexExtractionStrategy(custom=price_pattern)
# Method 3: Generate pattern with LLM assistance (one-time)
from crawl4ai import LLMConfig
async with AsyncWebCrawler() as crawler:
# Get sample HTML first
sample_result = await crawler.arun("https://example.com/products")
html = sample_result.markdown.fit_html
# Generate regex pattern once
pattern = RegexExtractionStrategy.generate_pattern(
label="price",
html=html,
query="Product prices in USD format",
llm_config=LLMConfig(provider="openai/gpt-4o-mini")
)
# Save pattern for reuse
import json
with open("price_pattern.json", "w") as f:
json.dump(pattern, f)
# Use pattern for extraction (no LLM calls)
strategy = RegexExtractionStrategy(custom=pattern)
result = await crawler.arun(
url="https://example.com/products",
config=CrawlerRunConfig(extraction_strategy=strategy)
)
# Process results
data = json.loads(result.extracted_content)
for item in data:
print(f"{item['label']}: {item['value']}")
CSS Extraction
from crawl4ai import JsonCssExtractionStrategy
# Define schema
schema = {
"name": "Product List",
"baseSelector": ".product-card",
"fields": [
{
"name": "title",
"selector": "h2.title",
"type": "text"
},
{
"name": "price",
"selector": ".price",
"type": "text",
"transform": "strip"
},
{
"name": "image",
"selector": "img",
"type": "attribute",
"attribute": "src"
}
]
}
# Create and use strategy
strategy = JsonCssExtractionStrategy(schema)
result = await crawler.arun(
url="https://example.com/products",
extraction_strategy=strategy
)
Content Chunking
from crawl4ai.chunking_strategy import OverlappingWindowChunking
from crawl4ai import LLMConfig
# Create chunking strategy
chunker = OverlappingWindowChunking(
window_size=500, # 500 words per chunk
overlap=50 # 50 words overlap
)
# Use with extraction strategy
strategy = LLMExtractionStrategy(
llm_config = LLMConfig(provider="ollama/llama2"),
chunking_strategy=chunker
)
result = await crawler.arun(
url="https://example.com/long-article",
extraction_strategy=strategy
)
Best Practices
- Choose the Right Strategy
- Use
RegexExtractionStrategyfor common data types like emails, phones, URLs, dates - Use
JsonCssExtractionStrategyfor well-structured HTML with consistent patterns - Use
LLMExtractionStrategyfor complex, unstructured content requiring reasoning -
Use
CosineStrategyfor content similarity and clustering -
Strategy Selection Guide
Is the target data a common type (email/phone/date/URL)?
→ RegexExtractionStrategy
Does the page have consistent HTML structure?
→ JsonCssExtractionStrategy or JsonXPathExtractionStrategy
Is the data semantically complex or unstructured?
→ LLMExtractionStrategy
Need to find content similar to a specific topic?
→ CosineStrategy
- Optimize Chunking
# For long documents
strategy = LLMExtractionStrategy(
chunk_token_threshold=2000, # Smaller chunks
overlap_rate=0.1 # 10% overlap
)
- Combine Strategies for Best Performance
# First pass: Extract structure with CSS
css_strategy = JsonCssExtractionStrategy(product_schema)
css_result = await crawler.arun(url, config=CrawlerRunConfig(extraction_strategy=css_strategy))
product_data = json.loads(css_result.extracted_content)
# Second pass: Extract specific fields with regex
descriptions = [product["description"] for product in product_data]
regex_strategy = RegexExtractionStrategy(
pattern=RegexExtractionStrategy.Email | RegexExtractionStrategy.PhoneUS,
custom={"dimension": r"\d+x\d+x\d+ (?:cm|in)"}
)
# Process descriptions with regex
for text in descriptions:
matches = regex_strategy.extract("", text) # Direct extraction
- Handle Errors
try:
result = await crawler.arun(
url="https://example.com",
extraction_strategy=strategy
)
if result.success:
content = json.loads(result.extracted_content)
except Exception as e:
print(f"Extraction failed: {e}")
- Monitor Performance
strategy = CosineStrategy(
verbose=True, # Enable logging
word_count_threshold=20, # Filter short content
top_k=5 # Limit results
)
- Cache Generated Patterns
# For RegexExtractionStrategy pattern generation
import json
from pathlib import Path
cache_dir = Path("./pattern_cache")
cache_dir.mkdir(exist_ok=True)
pattern_file = cache_dir / "product_pattern.json"
if pattern_file.exists():
with open(pattern_file) as f:
pattern = json.load(f)
else:
# Generate once with LLM
pattern = RegexExtractionStrategy.generate_pattern(...)
with open(pattern_file, "w") as f:
json.dump(pattern, f)
Overview
Version 0.7.3 introduces the Table Extraction Strategy Pattern, providing a more flexible and extensible approach to table extraction while maintaining full backward compatibility.
What's New
Strategy Pattern Implementation
Table extraction now follows the same strategy pattern used throughout Crawl4AI:
- Consistent Architecture: Aligns with extraction, chunking, and markdown strategies
- Extensibility: Easy to create custom table extraction strategies
- Better Separation: Table logic moved from content scraping to dedicated module
- Full Control: Fine-grained control over table detection and extraction
New Classes
from crawl4ai import (
TableExtractionStrategy, # Abstract base class
DefaultTableExtraction, # Current implementation (default)
NoTableExtraction # Explicitly disable extraction
)
Backward Compatibility
✅ All existing code continues to work without changes.
No Changes Required
If your code looks like this, it will continue to work:
# This still works exactly the same
config = CrawlerRunConfig(
table_score_threshold=7
)
result = await crawler.arun(url, config)
tables = result.tables # Same structure, same data
What Happens Behind the Scenes
When you don't specify a table_extraction strategy:
CrawlerRunConfigautomatically createsDefaultTableExtraction- It uses your
table_score_thresholdparameter - Tables are extracted exactly as before
- Results appear in
result.tableswith the same structure
New Capabilities
1. Explicit Strategy Configuration
You can now explicitly configure table extraction:
# New: Explicit control
strategy = DefaultTableExtraction(
table_score_threshold=7,
min_rows=2, # New: minimum row filter
min_cols=2, # New: minimum column filter
verbose=True # New: detailed logging
)
config = CrawlerRunConfig(
table_extraction=strategy
)
2. Disable Table Extraction
Improve performance when tables aren't needed:
# New: Skip table extraction entirely
config = CrawlerRunConfig(
table_extraction=NoTableExtraction()
)
# No CPU cycles spent on table detection/extraction
3. Custom Extraction Strategies
Create specialized extractors:
class MyTableExtractor(TableExtractionStrategy):
def extract_tables(self, element, **kwargs):
# Custom extraction logic
return custom_tables
config = CrawlerRunConfig(
table_extraction=MyTableExtractor()
)
Migration Scenarios
Scenario 1: Basic Usage (No Changes Needed)
Before (v0.7.2):
config = CrawlerRunConfig()
result = await crawler.arun(url, config)
for table in result.tables:
print(table['headers'])
After (v0.7.3):
# Exactly the same - no changes required
config = CrawlerRunConfig()
result = await crawler.arun(url, config)
for table in result.tables:
print(table['headers'])
Scenario 2: Custom Threshold (No Changes Needed)
Before (v0.7.2):
config = CrawlerRunConfig(
table_score_threshold=5
)
After (v0.7.3):
# Still works the same
config = CrawlerRunConfig(
table_score_threshold=5
)
# Or use new explicit approach for more control
strategy = DefaultTableExtraction(
table_score_threshold=5,
min_rows=2 # Additional filtering
)
config = CrawlerRunConfig(
table_extraction=strategy
)
Scenario 3: Advanced Filtering (New Feature)
Before (v0.7.2):
# Had to filter after extraction
config = CrawlerRunConfig(
table_score_threshold=5
)
result = await crawler.arun(url, config)
# Manual filtering
large_tables = [
t for t in result.tables
if len(t['rows']) >= 5 and len(t['headers']) >= 3
]
After (v0.7.3):
# Filter during extraction (more efficient)
strategy = DefaultTableExtraction(
table_score_threshold=5,
min_rows=5,
min_cols=3
)
config = CrawlerRunConfig(
table_extraction=strategy
)
result = await crawler.arun(url, config)
# result.tables already filtered
Code Organization Changes
Module Structure
Before (v0.7.2):
crawl4ai/
content_scraping_strategy.py
- LXMLWebScrapingStrategy
- is_data_table() # Table detection
- extract_table_data() # Table extraction
After (v0.7.3):
crawl4ai/
content_scraping_strategy.py
- LXMLWebScrapingStrategy
# Table methods removed, uses strategy
table_extraction.py (NEW)
- TableExtractionStrategy # Base class
- DefaultTableExtraction # Moved logic here
- NoTableExtraction # New option
Import Changes
New imports available (optional):
# These are now available but not required for existing code
from crawl4ai import (
TableExtractionStrategy,
DefaultTableExtraction,
NoTableExtraction
)
Performance Implications
No Performance Impact
For existing code, performance remains identical: - Same extraction logic - Same scoring algorithm - Same processing time
Performance Improvements Available
New options for better performance:
# Skip tables entirely (faster)
config = CrawlerRunConfig(
table_extraction=NoTableExtraction()
)
# Process only specific areas (faster)
config = CrawlerRunConfig(
css_selector="main.content",
table_extraction=DefaultTableExtraction(
min_rows=5, # Skip small tables
min_cols=3
)
)
Testing Your Migration
Verification Script
Run this to verify your extraction still works:
import asyncio
from crawl4ai import AsyncWebCrawler, CrawlerRunConfig
async def verify_extraction():
url = "your_url_here"
async with AsyncWebCrawler() as crawler:
# Test 1: Old approach
config_old = CrawlerRunConfig(
table_score_threshold=7
)
result_old = await crawler.arun(url, config_old)
# Test 2: New explicit approach
from crawl4ai import DefaultTableExtraction
config_new = CrawlerRunConfig(
table_extraction=DefaultTableExtraction(
table_score_threshold=7
)
)
result_new = await crawler.arun(url, config_new)
# Compare results
assert len(result_old.tables) == len(result_new.tables)
print(f"✓ Both approaches extracted {len(result_old.tables)} tables")
# Verify structure
for old, new in zip(result_old.tables, result_new.tables):
assert old['headers'] == new['headers']
assert old['rows'] == new['rows']
print("✓ Table content identical")
asyncio.run(verify_extraction())
Deprecation Notes
No Deprecations
- All existing parameters continue to work
table_score_thresholdinCrawlerRunConfigis still supported- No breaking changes
Internal Changes (Transparent to Users)
LXMLWebScrapingStrategy.is_data_table()- Moved toDefaultTableExtractionLXMLWebScrapingStrategy.extract_table_data()- Moved toDefaultTableExtraction
These methods were internal and not part of the public API.
Benefits of Upgrading
While not required, using the new pattern provides:
- Better Control: Filter tables during extraction, not after
- Performance Options: Skip extraction when not needed
- Extensibility: Create custom extractors for specific needs
- Consistency: Same pattern as other Crawl4AI strategies
- Future-Proof: Ready for upcoming advanced strategies
Troubleshooting
Issue: Different Number of Tables
Cause: Threshold or filtering differences
Solution:
# Ensure same threshold
strategy = DefaultTableExtraction(
table_score_threshold=7, # Match your old setting
min_rows=0, # No filtering (default)
min_cols=0 # No filtering (default)
)
Issue: Import Errors
Cause: Using new classes without importing
Solution:
# Add imports if using new features
from crawl4ai import (
DefaultTableExtraction,
NoTableExtraction,
TableExtractionStrategy
)
Issue: Custom Strategy Not Working
Cause: Incorrect method signature
Solution:
class CustomExtractor(TableExtractionStrategy):
def extract_tables(self, element, **kwargs): # Correct signature
# Not: extract_tables(self, html)
# Not: extract(self, element)
return tables_list
Getting Help
If you encounter issues:
- Check your
table_score_thresholdmatches previous settings - Verify imports if using new classes
- Enable verbose logging:
DefaultTableExtraction(verbose=True) - Review the Table Extraction Documentation
- Check examples
Summary
- ✅ Full backward compatibility - No code changes required
- ✅ Same results - Identical extraction behavior by default
- ✅ New options - Additional control when needed
- ✅ Better architecture - Consistent with Crawl4AI patterns
- ✅ Ready for future - Foundation for advanced strategies
The migration to v0.7.3 is seamless with no required changes while providing new capabilities for those who need them.
