详解AI采集框架Crawl4AI,打造智能网络爬虫

使用Crawl4AI构建高效AI爬虫与数据提取工具。

1 介绍

Crawl4AI这个开源Python库,专门用来简化网页爬取和数据提取的工作。它不仅功能强大、灵活,而且全异步的设计让处理速度更快,稳定性更好。无论是构建AI项目还是提升语言模型的性能,Crawl4AI都能帮您简化工作流程。

你可以直接在Python项目中使用,或者将其集成到REST API中,实现快速、稳定的数据爬取和处理。这样,无论是数据的实时获取还是后续的分析处理,都能更加得心应手。

2 快速开始

立刻上手 Crawl4AI!以下是个简单的例子,展示了其强大的异步能力:

import asyncio   from crawl4ai import AsyncWebCrawler      asyncdef main():       # 初始化异步网页爬虫       asyncwith AsyncWebCrawler(verbose=True) as crawler:           # 爬取指定的 URL           result = await crawler.arun(url="https://www.nbcnews.com/business")           # 以 Markdown 格式显示提取的内容           print(result.markdown)      # 执行异步主函数   if __name__ == "__main__":       asyncio.run(main())   

解释:

  • 导入库:从crawl4ai库中导入AsyncWebCrawlerasyncio模块。

  • 创建异步上下文:使用异步上下文管理器实例化AsyncWebCrawler

  • 运行爬虫:使用arun() 法异步爬取指定的 URL 并提取有意义的内容。

  • 打印结果:输出提取的内容,格式化为 Markdown。

  • 执行异步函数:使用asyncio.run()执行异步的main函数。

3 特性亮点

Crawl4AI具备以下核心特性,让网页爬取和数据提取工作更加高效:

  • 开源免费:无额外费用,开源可信赖。

  • 快速性能:速度超越许多付费工具。

  • 多样输出:支持JSON、清洁HTML、Markdown格式。

  • 多URL并发:一次性处理多个网页,提升效率。

  • 媒体提取:全面抓取图片、音频、视频等。

  • 链接全收集:不遗漏任何内外链接。

  • 元数据抽取:深入提取网页信息。

  • 自定义操作:自定义请求头、认证,修改页面后再爬取。

  • 用户代理模拟:模拟不同设备访问。

  • 页面截图:快速获取网页视觉快照。

  • JavaScript支持:执行JS获取动态内容。

  • 数据结构化:精确提取结构化数据。

  • 智能提取技术:使用余弦聚类和LLM技术。

  • CSS选择器:精准定位数据。

  • 指令优化:通过指令提升提取效果。

  • 代理配置:增强访问权限和隐私保护。

  • 会话管理:轻松处理多页爬取。

  • 异步架构:提升性能和可扩展性。

4 安装指南

Crawl4AI提供了多种安装方式,以适应不同的使用场景。以下是几种常用的安装方法:

4.1 基本安装(推荐)

对于大多数网页爬取和数据抓取任务,可以直接使用pip进行安装:

pip install crawl4ai   

这样,默认安装的是Crawl4AI的异步版本,使用Playwright进行网页爬取。

注意:如果安装时遇到Playwright相关错误,可以通过以下命令手动安装Playwright:

playwright install   

或者,安装特定版本的Chromium:

python -m playwright install chromium   

4.2 同步版本安装

如果需要使用Selenium的同步版本,可以使用以下命令:

pip install crawl4ai[sync]   

4.3 开发者安装

对于想要参与项目开发,修改源代码的贡献者,可以通过以下步骤进行安装:

git clone https://github.com/unclecode/crawl4ai.git   cd crawl4ai   pip install -e .   

5 高级应用

想要充分发挥Crawl4AI的能力?来看看这些高级功能和应用案例:

5.1 执行JavaScript和使用CSS选择器

可以利用Crawl4AI执行自定义JavaScript代码,以及通过CSS选择器精准定位页面元素,从而提升爬取任务的效率和精确度。这让你能够更灵活地处理复杂的网页数据抓取需求。

import asyncio   from crawl4ai import AsyncWebCrawler      asyncdef main():       asyncwith 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,               css_selector="article.tease-card",               bypass_cache=True           )           print(result.extracted_content)      if __name__ == "__main__":       asyncio.run(main())   

5.2 使用代理

通过将爬取任务路由到代理,增强你的隐私和访问权限。

import asyncio   from crawl4ai import AsyncWebCrawler      async def main():       async with AsyncWebCrawler(verbose=True, proxy="http://127.0.0.1:7890") as crawler:           result = await crawler.arun(               url="https://www.nbcnews.com/business",               bypass_cache=True           )           print(result.markdown)      if __name__ == "__main__":       asyncio.run(main())   

5.3 不使用 LLM 提取结构化数据

使用JsonCssExtractionStrategy精确提取使用 CSS 选择器的结构化数据。

import asyncio   import json   from crawl4ai import AsyncWebCrawler   from crawl4ai.extraction_strategy import JsonCssExtractionStrategy      asyncdef extract_news_teasers():       schema = {           "name": "News Teaser Extractor",           "baseSelector": ".wide-tease-item__wrapper",           "fields": [               {"name": "category", "selector": ".unibrow span[data-testid='unibrow-text']", "type": "text"},               {"name": "headline", "selector": ".wide-tease-item__headline", "type": "text"},               {"name": "summary", "selector": ".wide-tease-item__description", "type": "text"},               {"name": "time", "selector": "[data-testid='wide-tease-date']", "type": "text"},               {                   "name": "image",                   "type": "nested",                   "selector": "picture.teasePicture img",                   "fields": [                       {"name": "src", "type": "attribute", "attribute": "src"},                       {"name": "alt", "type": "attribute", "attribute": "alt"},                   ],               },               {"name": "link", "selector": "a[href]", "type": "attribute", "attribute": "href"},           ],       }       extraction_strategy = JsonCssExtractionStrategy(schema, verbose=True)       asyncwith AsyncWebCrawler(verbose=True) as crawler:           result = await crawler.arun(               url="https://www.nbcnews.com/business",               extraction_strategy=extraction_strategy,               bypass_cache=True,           )           assert result.success, "Failed to crawl the page"           news_teasers = json.loads(result.extracted_content)           print(f"Successfully extracted {len(news_teasers)} news teasers")           print(json.dumps(news_teasers[0], indent=2))      if __name__ == "__main__":       asyncio.run(extract_news_teasers())   

5.4 使用 OpenAI 提取结构化数据

利用 OpenAI 的能力动态提取和结构化数据。

import os   import asyncio   from crawl4ai import AsyncWebCrawler   from crawl4ai.extraction_strategy import LLMExtractionStrategy   from pydantic import BaseModel, Field      class OpenAIModelFee(BaseModel):       model_name: str = Field(..., description="Name of the OpenAI model.")       input_fee: str = Field(..., description="Fee for input token for the OpenAI model.")       output_fee: str = Field(..., description="Fee for output token for the OpenAI model.")      asyncdef main():       asyncwith AsyncWebCrawler(verbose=True) as crawler:           result = await crawler.arun(               url='https://openai.com/api/pricing/',               word_count_threshold=1,               extraction_strategy=LLMExtractionStrategy(                   provider="openai/gpt-4   o",                   api_token=os.getenv('OPENAI_API_KEY'),                    schema=OpenAIModelFee.schema(),                   extraction_type="schema",                   instruction="""From the crawled content, extract all mentioned model names along with their fees for input and output tokens.       Do not miss any models in the entire content. One extracted model JSON format should look like this:       {"model_name": "GPT-4", "input_fee": "US$10.00 / 1M tokens", "output_fee": "US$30.00 / 1M tokens"}."""               ),                           bypass_cache=True,           )           print(result.extracted_content)      if __name__ == "__main__":       asyncio.run(main())   

5.5 会话管理 & 动态内容爬取

处理复杂的场景,如爬取通过 JavaScript 加载动态内容的多个页面。

import asyncio   import re   from bs4 import BeautifulSoup   from crawl4ai import AsyncWebCrawler      asyncdef crawl_typescript_commits():       first_commit = ""       asyncdef on_execution_started(page):           nonlocal first_commit            try:               whileTrue:                   await page.wait_for_selector('li.Box-sc-g0xbh4-0 h4')                   commit = await page.query_selector('li.Box-sc-g0xbh4-0 h4')                   commit = await commit.evaluate('(element) => element.textContent')                   commit = re.sub(r'\s+', '', commit)                   if commit and commit != first_commit:                       first_commit = commit                       break                   await asyncio.sleep(0.5)           except Exception as e:               print(f"Warning: New content didn't appear after JavaScript execution: {e}")       asyncwith AsyncWebCrawler(verbose=True) as crawler:           crawler.crawler_strategy.set_hook('on_execution_started', on_execution_started)           url = "https://github.com/microsoft/TypeScript/commits/main"           session_id = "typescript_commits_session"           all_commits = []           js_next_page = """           const button = document.querySelector('a[data-testid="pagination-next-button"]');           if (button) button.click();           """           for page in range(3):  # Crawl 3 pages               result = await crawler.arun(                   url=url,                   session_id=session_id,                   css_selector="li.Box-sc-g0xbh4-0",                   js=js_next_page if page > 0elseNone,                   bypass_cache=True,                   js_only=page > 0               )               assert result.success, f"Failed to crawl page {page + 1}"               soup = BeautifulSoup(result.cleaned_html, 'html.parser')               commits = soup.select("li.Box-sc-g0xbh4-0")               all_commits.extend(commits)               print(f"Page {page + 1}: Found {len(commits)} commits")           await crawler.crawler_strategy.kill_session(session_id)           print(f"Successfully crawled {len(all_commits)} commits across 3 pages")      if __name__ == "__main__":       asyncio.run(crawl_typescript_commits())   

6 性能对比

Crawl4AI在设计上注重速度和效率,性能持续超越许多付费服务。以下是我们的性能测试结果:

要点总结:

  • 简单爬取:Crawl4AI的速度是Firecrawl的4倍以上。

  • 带JavaScript执行:即使在执行JavaScript加载更多内容的情况下(图片数量增加一倍),Crawl4AI的速度依然远超Firecrawl的简单爬取。

如何学习大模型 AI ?

由于新岗位的生产效率,要优于被取代岗位的生产效率,所以实际上整个社会的生产效率是提升的。

但是具体到个人,只能说是:

“最先掌握AI的人,将会比较晚掌握AI的人有竞争优势”。

这句话,放在计算机、互联网、移动互联网的开局时期,都是一样的道理。

我在一线互联网企业工作十余年里,指导过不少同行后辈。帮助很多人得到了学习和成长。

我意识到有很多经验和知识值得分享给大家,也可以通过我们的能力和经验解答大家在人工智能学习中的很多困惑,所以在工作繁忙的情况下还是坚持各种整理和分享。但苦于知识传播途径有限,很多互联网行业朋友无法获得正确的资料得到学习提升,故此将并将重要的AI大模型资料包括AI大模型入门学习思维导图、精品AI大模型学习书籍手册、视频教程、实战学习等录播视频免费分享出来。

在这里插入图片描述

第一阶段(10天):初阶应用

该阶段让大家对大模型 AI有一个最前沿的认识,对大模型 AI 的理解超过 95% 的人,可以在相关讨论时发表高级、不跟风、又接地气的见解,别人只会和 AI 聊天,而你能调教 AI,并能用代码将大模型和业务衔接。

  • 大模型 AI 能干什么?
  • 大模型是怎样获得「智能」的?
  • 用好 AI 的核心心法
  • 大模型应用业务架构
  • 大模型应用技术架构
  • 代码示例:向 GPT-3.5 灌入新知识
  • 提示工程的意义和核心思想
  • Prompt 典型构成
  • 指令调优方法论
  • 思维链和思维树
  • Prompt 攻击和防范

第二阶段(30天):高阶应用

该阶段我们正式进入大模型 AI 进阶实战学习,学会构造私有知识库,扩展 AI 的能力。快速开发一个完整的基于 agent 对话机器人。掌握功能最强的大模型开发框架,抓住最新的技术进展,适合 Python 和 JavaScript 程序员。

  • 为什么要做 RAG
  • 搭建一个简单的 ChatPDF
  • 检索的基础概念
  • 什么是向量表示(Embeddings)
  • 向量数据库与向量检索
  • 基于向量检索的 RAG
  • 搭建 RAG 系统的扩展知识
  • 混合检索与 RAG-Fusion 简介
  • 向量模型本地部署

第三阶段(30天):模型训练

恭喜你,如果学到这里,你基本可以找到一份大模型 AI相关的工作,自己也能训练 GPT 了!通过微调,训练自己的垂直大模型,能独立训练开源多模态大模型,掌握更多技术方案。

到此为止,大概2个月的时间。你已经成为了一名“AI小子”。那么你还想往下探索吗?

  • 为什么要做 RAG
  • 什么是模型
  • 什么是模型训练
  • 求解器 & 损失函数简介
  • 小实验2:手写一个简单的神经网络并训练它
  • 什么是训练/预训练/微调/轻量化微调
  • Transformer结构简介
  • 轻量化微调
  • 实验数据集的构建

第四阶段(20天):商业闭环

对全球大模型从性能、吞吐量、成本等方面有一定的认知,可以在云端和本地等多种环境下部署大模型,找到适合自己的项目/创业方向,做一名被 AI 武装的产品经理。

  • 硬件选型
  • 带你了解全球大模型
  • 使用国产大模型服务
  • 搭建 OpenAI 代理
  • 热身:基于阿里云 PAI 部署 Stable Diffusion
  • 在本地计算机运行大模型
  • 大模型的私有化部署
  • 基于 vLLM 部署大模型
  • 案例:如何优雅地在阿里云私有部署开源大模型
  • 部署一套开源 LLM 项目
  • 内容安全
  • 互联网信息服务算法备案

学习是一个过程,只要学习就会有挑战。天道酬勤,你越努力,就会成为越优秀的自己。

如果你能在15天内完成所有的任务,那你堪称天才。然而,如果你能完成 60-70% 的内容,你就已经开始具备成为一名大模型 AI 的正确特征了。

这份完整版的大模型 AI 学习资料已经上传CSDN,朋友们如果需要可以微信扫描下方CSDN官方认证二维码免费领取【保证100%免费

在这里插入图片描述

### 关于 Crawl4AI 的教程与使用指南 #### 安装方法 对于希望使用 pip 进行基本安装的用户而言,可以运行如下命令来获取最新发布的稳定版本: ```bash pip install crawl4ai ``` 如果倾向于开发环境或是想要尝试最新的特性,则可以通过 GitHub 获取源码并进行本地构建[^1]。 #### 快速启动实例 为了帮助初学者快速上手,官方提供了简单的例子用于展示如何创建一个基础的任务。下面是一个完整的 Python 脚本示例,它展示了怎样定义目标网站以及配置必要的参数以发起请求: ```python from crawl4ai import Crawl4AIClient, TaskConfig client = Crawl4AIClient() config = TaskConfig( url="http://example.com", ) async def main(): result = await client.run_task(config) print(result) if __name__ == "__main__": import asyncio asyncio.run(main()) ``` 这段代码初始化了一个客户端对象,并设置了要访问的目标 URL 。通过调用 `run_task` 方法传入配置信息即可开始执行抓取操作。 #### 高级功能探索 除了上述的基础功能外,还支持更复杂的场景如 JavaScript 渲染页面解析、利用 CSS 选择器定位特定 HTML 元素、借助代理服务器隐藏身份等。特别是当涉及到动态加载的内容时,这些能力显得尤为重要。 另外,在处理非结构化的网页内容方面表现出色;即使不依赖大型语言模型也能有效地抽取所需的信息片段。而对于那些追求更高精度的应用场合来说,还可以集成 OpenAI API 来增强自然语言理解的能力[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值