参数指南(新方法)
在 Crawl4AI 的最新配置模型中,几乎所有曾经直接传递给arun()
现在是CrawlerRunConfig
. 调用时arun()
,您提供:
以下是可以放入的参数的有序视图CrawlerRunConfig
,按其功能区域划分。对于浏览器设置(例如,headless
,browser_type
),请参阅BrowserConfig 。
1. 核心使用
from crawl4ai import AsyncWebCrawler, CrawlerRunConfig, CacheMode
async def main():
run_config = CrawlerRunConfig(
verbose=True, # Detailed logging
cache_mode=CacheMode.ENABLED, # Use normal read/write cache
check_robots_txt=True, # Respect robots.txt rules
# ... other parameters
)
async with AsyncWebCrawler() as crawler:
result = await crawler.arun(
url="https://example.com",
config=run_config
)
# Check if blocked by robots.txt
if not result.success and result.status_code == 403:
print(f"Error: {result.error_message}")
关键字段:-verbose=True
记录每个爬行步骤。-cache_mode
决定如何读取/写入本地抓取缓存。
2. 缓存控制
(默认:CacheMode.ENABLED
) 使用内置枚举CacheMode
:
- :正常缓存 - 如果可用则读取,如果缺失则写入。
- :无缓存——始终重新获取页面。
- :仅从缓存读取;没有新的写入。
- :写入缓存但不读取现有数据。
- :跳过此抓取的读取缓存(但如果这样设置的话,它可能仍会写入)。
附加标志:
- 就像
CacheMode.BYPASS
。 - 就像
CacheMode.DISABLED
。 - 就像
CacheMode.WRITE_ONLY
。 - 就像
CacheMode.READ_ONLY
。
3.内容处理与选择
3.1 文本处理
run_config = CrawlerRunConfig(
word_count_threshold=10, # Ignore text blocks <10 words
only_text=False, # If True, tries to remove non-text elements
keep_data_attributes=False # Keep or discard data-* attributes
)
3.2 内容选择
run_config = CrawlerRunConfig(
css_selector=".main-content", # Focus on .main-content region only
excluded_tags=["form", "nav"], # Remove entire tag blocks
remove_forms=True, # Specifically strip <form> elements
remove_overlay_elements=True, # Attempt to remove modals/popups
)
3.3 链接处理
run_config = CrawlerRunConfig(
exclude_external_links=True, # Remove external links from final content
exclude_social_media_links=True, # Remove links to known social sites
exclude_domains=["ads.example.com"], # Exclude links to these domains
exclude_social_media_domains=["facebook.com","twitter.com"], # Extend the default list
)
3.4 媒体过滤
4. 页面导航和时间
4.1 基本浏览器流程
run_config = CrawlerRunConfig(
wait_for="css:.dynamic-content", # Wait for .dynamic-content
delay_before_return_html=2.0, # Wait 2s before capturing final HTML
page_timeout=60000, # Navigation & script timeout (ms)
)
关键字段:
- :
- 或者
- 例如
js:() => document.querySelectorAll('.item').length > 10
。 - &
max_range
:定义随机延迟arun_many()
呼叫。 - :爬取多个URL时的并发限制。
4.2 JavaScript执行
run_config = CrawlerRunConfig(
js_code=[
"window.scrollTo(0, document.body.scrollHeight);",
"document.querySelector('.load-more')?.click();"
],
js_only=False
)
- 可以是单个字符串或字符串列表。
- 意思是“我将继续在同一个会话中使用新的 JS 步骤,而不是新的完整导航。”
4.3 反机器人
-magic=True
tries multiple stealth features.
- simulate_user=True
mimics mouse movements or random delays.
- override_navigator=True
fakes some navigator properties (like user agent checks).
5. 会话管理
:
If re-used in subsequentarun()
calls, the same tab/page context is continued (helpful for multi-step tasks or stateful browsing).
6. 屏幕截图、PDF 和媒体选项
run_config = CrawlerRunConfig(
screenshot=True, # Grab a screenshot as base64
screenshot_wait_for=1.0, # Wait 1s before capturing
pdf=True, # Also produce a PDF
image_description_min_word_threshold=5, # If analyzing alt text
image_score_threshold=3, # Filter out low-score images
)
result.screenshot
→ Base64 screenshot string.
- result.pdf
→ Byte array with PDF data.
7.提取策略
对于高级数据提取(基于 CSS/LLM),设置extraction_strategy
:
提取的数据将出现在result.extracted_content
。
8.综合示例
下面是一个包含多个参数的代码片段:
import asyncio
from crawl4ai import AsyncWebCrawler, CrawlerRunConfig, CacheMode
from crawl4ai import JsonCssExtractionStrategy
async def main():
# Example schema
schema = {
"name": "Articles",
"baseSelector": "article.post",
"fields": [
{"name": "title", "selector": "h2", "type": "text"},
{"name": "link", "selector": "a", "type": "attribute", "attribute": "href"}
]
}
run_config = CrawlerRunConfig(
# Core
verbose=True,
cache_mode=CacheMode.ENABLED,
check_robots_txt=True, # Respect robots.txt rules
# Content
word_count_threshold=10,
css_selector="main.content",
excluded_tags=["nav", "footer"],
exclude_external_links=True,
# Page & JS
js_code="document.querySelector('.show-more')?.click();",
wait_for="css:.loaded-block",
page_timeout=30000,
# Extraction
extraction_strategy=JsonCssExtractionStrategy(schema),
# Session
session_id="persistent_session",
# Media
screenshot=True,
pdf=True,
# Anti-bot
simulate_user=True,
magic=True,
)
async with AsyncWebCrawler() as crawler:
result = await crawler.arun("https://example.com/posts", config=run_config)
if result.success:
print("HTML length:", len(result.cleaned_html))
print("Extraction JSON:", result.extracted_content)
if result.screenshot:
print("Screenshot length:", len(result.screenshot))
if result.pdf:
print("PDF bytes length:", len(result.pdf))
else:
print("Error:", result.error_message)
if __name__ == "__main__":
asyncio.run(main())
我们涵盖的内容:
1. 抓取主内容区域,忽略外部链接。2. 运行 JavaScript 并点击“.show-more”。3. 等待“.loaded-block”出现。4. 生成最终页面的截图和 PDF。5. 使用基于 CSS 的提取策略提取重复的“article.post”元素。
9.最佳实践
1.使用BrowserConfig
用于全局浏览器设置(无头浏览器、用户代理)。2. 使用CrawlerRunConfig
处理特定的爬取需求:内容过滤、缓存、JS、截图、提取等。3. 保持运行配置中的参数一致——尤其是在您属于拥有多个爬取任务的大型代码库时。4. 限制大并发(semaphore_count
)如果网站或您的系统无法处理。5. 对于动态页面,请设置js_code
或者scan_full_page
所以你加载所有内容。
10. 结论
所有参数都曾经是arun()
现在属于CrawlerRunConfig
.这种方法:
- 使代码更清晰、更易于维护。
- 最大限度地减少关于哪些参数影响全局行为与哪些参数影响每次爬行行为的混淆。
- 允许您为不同的页面或任务创建可重复使用的配置对象。
如需完整参考,请查看CrawlerRunConfig 文档。
祝您使用结构化、灵活的配置方法顺利爬行!