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 StartedRust0152- DDeepSeek-V4-ProDeepSeek-V4-Pro(总参数 1.6 万亿,激活 49B)面向复杂推理和高级编程任务,在代码竞赛、数学推理、Agent 工作流等场景表现优异,性能接近国际前沿闭源模型。Python00
LongCat-Video-Avatar-1.5最新开源LongCat-Video-Avatar 1.5 版本,这是一款经过升级的开源框架,专注于音频驱动人物视频生成的极致实证优化与生产级就绪能力。该版本在 LongCat-Video 基础模型之上构建,可生成高度稳定的商用级虚拟人视频,支持音频-文本转视频(AT2V)、音频-文本-图像转视频(ATI2V)以及视频续播等原生任务,并能无缝兼容单流与多流音频输入。00
auto-devAutoDev 是一个 AI 驱动的辅助编程插件。AutoDev 支持一键生成测试、代码、提交信息等,还能够与您的需求管理系统(例如Jira、Trello、Github Issue 等)直接对接。 在IDE 中,您只需简单点击,AutoDev 会根据您的需求自动为您生成代码。Kotlin03
Intern-S2-PreviewIntern-S2-Preview,这是一款高效的350亿参数科学多模态基础模型。除了常规的参数与数据规模扩展外,Intern-S2-Preview探索了任务扩展:通过提升科学任务的难度、多样性与覆盖范围,进一步释放模型能力。Python00
skillhubopenJiuwen 生态的 Skill 托管与分发开源方案,支持自建与可选 ClawHub 兼容。Python0112
项目优选
收起
暂无描述
Dockerfile
733
4.75 K
Ascend Extension for PyTorch
Python
618
795
openEuler内核是openEuler操作系统的核心,既是系统性能与稳定性的基石,也是连接处理器、设备与服务的桥梁。
C
433
395
本项目是CANN提供的数学类基础计算算子库,实现网络在NPU上加速计算。
C++
1.01 K
1.01 K
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
1.18 K
152
deepin linux kernel
C
29
16
华为昇腾面向大规模分布式训练的多模态大模型套件,支撑多模态生成、多模态理解。
Python
145
237
暂无简介
Dart
983
252
昇腾LLM分布式训练框架
Python
166
198
🎉 (RuoYi)官方仓库 基于SpringBoot,Spring Security,JWT,Vue3 & Vite、Element Plus 的前后端分离权限管理系统
Vue
1.68 K
989