Crawl4AI 快速入门指南:异步网页爬取与AI数据提取实战
2026-02-03 05:43:13作者:翟萌耘Ralph
项目概述
Crawl4AI 是一个专为AI应用设计的现代化异步网页爬取框架,它简化了从网页中提取结构化数据的过程,特别适合为大型语言模型(LLMs)提供训练数据或实时信息获取。该框架集成了智能内容提取、动态页面处理等高级功能,让开发者能够轻松应对各种复杂的网页爬取场景。
环境准备
安装依赖
首先需要安装Crawl4AI核心库及其依赖项:
!pip install crawl4ai
!pip install nest_asyncio
!playwright install
由于Crawl4AI基于异步IO设计,我们需要启用nest_asyncio来兼容Jupyter等环境:
import asyncio
import nest_asyncio
nest_asyncio.apply()
基础爬取示例
简单网页内容获取
最基本的爬取功能只需要几行代码:
from crawl4ai import AsyncWebCrawler
async def simple_crawl():
async with AsyncWebCrawler() as crawler:
result = await crawler.arun(
url="https://www.nbcnews.com/business",
bypass_cache=True
)
print(result.markdown.raw_markdown[:500]) # 打印前500个字符
asyncio.run(simple_crawl())
这段代码会:
- 创建异步爬虫实例
- 访问指定URL
- 返回包含原始Markdown格式的内容
- 打印前500个字符作为示例
高级功能探索
动态内容处理
现代网页大量使用JavaScript动态加载内容,Crawl4AI提供了多种方式处理这种情况:
async def crawl_dynamic_content():
async with AsyncWebCrawler(verbose=True) as crawler:
js_code = [
"const loadMoreButton = Array.from(document.querySelectorAll('button'))"
".find(button => button.textContent.includes('Load More'));"
"loadMoreButton && loadMoreButton.click();"
]
result = await crawler.arun(
url="https://www.nbcnews.com/business",
js_code=js_code,
bypass_cache=True,
)
print(result.markdown.raw_markdown[:500])
关键参数说明:
js_code: 执行自定义JavaScript代码wait_for: 可指定CSS选择器或函数,等待特定元素出现verbose: 开启详细日志
内容清洗与优化
Crawl4AI内置了智能内容清洗功能:
async def clean_content():
async with AsyncWebCrawler() as crawler:
result = await crawler.arun(
url="https://janineintheworld.com/places-to-visit-in-central-mexico",
excluded_tags=['nav', 'footer', 'aside'], # 排除导航等非主要内容
remove_overlay_elements=True, # 移除弹窗等覆盖元素
word_count_threshold=10, # 内容块最小字数阈值
)
print(f"清洗前长度: {len(result.markdown.raw_markdown)}")
print(f"清洗后长度: {len(result.markdown.fit_markdown)}")
print(result.markdown.fit_markdown[:1000])
链接分析与过滤
Crawl4AI可以智能分类和分析页面链接:
async def link_analysis():
async with AsyncWebCrawler() as crawler:
result = await crawler.arun(
url="https://www.nbcnews.com/business",
exclude_external_links=True, # 排除外部链接
exclude_social_media_links=True # 排除社交媒体链接
)
print(f"内部链接数: {len(result.links['internal'])}")
print(f"外部链接数: {len(result.links['external'])}")
for link in result.links['internal'][:5]:
print(f"链接: {link['href']}\n文本: {link['text']}\n")
媒体资源处理
提取页面中的图片等媒体资源:
async def media_handling():
async with AsyncWebCrawler() as crawler:
result = await crawler.arun(
url="https://www.nbcnews.com/business",
exclude_external_images=False, # 包含外部图片
screenshot=True # 生成页面截图
)
for img in result.media['images'][:5]:
print(f"图片URL: {img['src']}, 描述: {img['alt']}, 相关性评分: {img['score']}")
高级技巧
使用钩子自定义流程
Crawl4AI提供了多种钩子(Hook)来扩展功能:
async def custom_hook_workflow():
async with AsyncWebCrawler() as crawler:
# 设置导航前钩子
crawler.crawler_strategy.set_hook(
"before_goto",
lambda page: print("[Hook] 准备导航...")
)
result = await crawler.arun(
url="https://crawl4ai.com",
bypass_cache=True
)
print(result.markdown.raw_markdown[:500])
可用钩子包括:
on_browser_created: 浏览器创建时触发before_goto: 页面导航前触发after_goto: 页面导航后触发on_execution_started: JavaScript执行前触发before_return_html: 返回HTML前触发
会话保持爬取
对于需要登录或多步骤操作的场景,可以使用会话保持:
async def session_based_crawl():
async with AsyncWebCrawler() as crawler:
# 第一步操作
await crawler.arun(url="https://example.com/login")
# 第二步操作,保持相同会话
result = await crawler.arun(url="https://example.com/dashboard")
print(result.markdown.raw_markdown)
最佳实践建议
- 合理设置缓存:对于频繁访问的页面,合理利用缓存可以显著提高性能
- 错误处理:添加适当的异常处理应对网络问题
- 速率限制:遵守目标网站的robots.txt规则,添加适当延迟
- 资源管理:使用上下文管理器(async with)确保资源正确释放
- 日志记录:开启verbose模式调试复杂爬取过程
Crawl4AI通过其简洁的API和强大的功能,为AI数据采集提供了高效可靠的解决方案。无论是简单的静态页面还是复杂的动态应用,都能轻松应对。
登录后查看全文
热门项目推荐
相关项目推荐
atomcodeClaude Code 的开源替代方案。连接任意大模型,编辑代码,运行命令,自动验证 — 全自动执行。用 Rust 构建,极致性能。 | An open-source alternative to Claude Code. Connect any LLM, edit code, run commands, and verify changes — autonomously. Built in Rust for speed. Get StartedRust098- DDeepSeek-V4-ProDeepSeek-V4-Pro(总参数 1.6 万亿,激活 49B)面向复杂推理和高级编程任务,在代码竞赛、数学推理、Agent 工作流等场景表现优异,性能接近国际前沿闭源模型。Python00
MiMo-V2.5-ProMiMo-V2.5-Pro作为旗舰模型,擅⻓处理复杂Agent任务,单次任务可完成近千次⼯具调⽤与⼗余轮上 下⽂压缩。Python00
GLM-5.1GLM-5.1是智谱迄今最智能的旗舰模型,也是目前全球最强的开源模型。GLM-5.1大大提高了代码能力,在完成长程任务方面提升尤为显著。和此前分钟级交互的模型不同,它能够在一次任务中独立、持续工作超过8小时,期间自主规划、执行、自我进化,最终交付完整的工程级成果。Jinja00
Kimi-K2.6Kimi K2.6 是一款开源的原生多模态智能体模型,在长程编码、编码驱动设计、主动自主执行以及群体任务编排等实用能力方面实现了显著提升。Python00
MiniMax-M2.7MiniMax-M2.7 是我们首个深度参与自身进化过程的模型。M2.7 具备构建复杂智能体应用框架的能力,能够借助智能体团队、复杂技能以及动态工具搜索,完成高度精细的生产力任务。Python00
项目优选
收起
deepin linux kernel
C
28
16
Claude Code 的开源替代方案。连接任意大模型,编辑代码,运行命令,自动验证 — 全自动执行。用 Rust 构建,极致性能。 | An open-source alternative to Claude Code. Connect any LLM, edit code, run commands, and verify changes — autonomously. Built in Rust for speed.
Get Started
Rust
566
98
暂无描述
Dockerfile
708
4.51 K
openEuler内核是openEuler操作系统的核心,既是系统性能与稳定性的基石,也是连接处理器、设备与服务的桥梁。
C
413
339
本项目是CANN提供的数学类基础计算算子库,实现网络在NPU上加速计算。
C++
958
955
Ascend Extension for PyTorch
Python
572
694
🎉 (RuoYi)官方仓库 基于SpringBoot,Spring Security,JWT,Vue3 & Vite、Element Plus 的前后端分离权限管理系统
Vue
1.6 K
940
🍒 Cherry Studio 是一款支持多个 LLM 提供商的桌面客户端
TypeScript
1.42 K
116
AI 将任意文档转换为精美可编辑的 PPTX 演示文稿 — 无需设计基础 | 包含 15 个案例、229 页内容
Python
80
5
暂无简介
Dart
951
235