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数据采集提供了高效可靠的解决方案。无论是简单的静态页面还是复杂的动态应用,都能轻松应对。
登录后查看全文
热门项目推荐
相关项目推荐
GLM-5智谱 AI 正式发布 GLM-5,旨在应对复杂系统工程和长时域智能体任务。Jinja00
GLM-5-w4a8GLM-5-w4a8基于混合专家架构,专为复杂系统工程与长周期智能体任务设计。支持单/多节点部署,适配Atlas 800T A3,采用w4a8量化技术,结合vLLM推理优化,高效平衡性能与精度,助力智能应用开发Jinja00
jiuwenclawJiuwenClaw 是一款基于openJiuwen开发的智能AI Agent,它能够将大语言模型的强大能力,通过你日常使用的各类通讯应用,直接延伸至你的指尖。Python0193- QQwen3.5-397B-A17BQwen3.5 实现了重大飞跃,整合了多模态学习、架构效率、强化学习规模以及全球可访问性等方面的突破性进展,旨在为开发者和企业赋予前所未有的能力与效率。Jinja00
AtomGit城市坐标计划AtomGit 城市坐标计划开启!让开源有坐标,让城市有星火。致力于与城市合伙人共同构建并长期运营一个健康、活跃的本地开发者生态。01
awesome-zig一个关于 Zig 优秀库及资源的协作列表。Makefile00
热门内容推荐
最新内容推荐
pi-mono自定义工具开发实战指南:从入门到精通3个实时风控价值:Flink CDC+ClickHouse在金融反欺诈的实时监测指南Docling 实用指南:从核心功能到配置实践自动化票务处理系统在高并发抢票场景中的技术实现:从手动抢购痛点到智能化解决方案OpenCore Legacy Patcher显卡驱动适配指南:让老Mac焕发新生7个维度掌握Avalonia:跨平台UI框架从入门到架构师Warp框架安装部署解决方案:从环境诊断到容器化实战指南突破移动瓶颈:kkFileView的5层适配架构与全场景实战指南革新智能交互:xiaozhi-esp32如何实现百元级AI对话机器人如何打造专属AI服务器?本地部署大模型的全流程实战指南
项目优选
收起
deepin linux kernel
C
27
12
OpenHarmony documentation | OpenHarmony开发者文档
Dockerfile
601
4.04 K
🔥LeetCode solutions in any programming language | 多种编程语言实现 LeetCode、《剑指 Offer(第 2 版)》、《程序员面试金典(第 6 版)》题解
Java
69
21
Ascend Extension for PyTorch
Python
441
531
AscendNPU-IR是基于MLIR(Multi-Level Intermediate Representation)构建的,面向昇腾亲和算子编译时使用的中间表示,提供昇腾完备表达能力,通过编译优化提升昇腾AI处理器计算效率,支持通过生态框架使能昇腾AI处理器与深度调优
C++
112
170
🎉 (RuoYi)官方仓库 基于SpringBoot,Spring Security,JWT,Vue3 & Vite、Element Plus 的前后端分离权限管理系统
Vue
1.46 K
825
本项目是CANN提供的数学类基础计算算子库,实现网络在NPU上加速计算。
C++
922
770
暂无简介
Dart
847
204
React Native鸿蒙化仓库
JavaScript
321
375
openGauss kernel ~ openGauss is an open source relational database management system
C++
174
249