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

大家好,Crawl4AI作为开源Python库,专门用来简化网页爬取和数据提取的工作。它不仅功能强大、灵活,而且全异步的设计让处理速度更快,稳定性更好。无论是构建AI项目还是提升语言模型的性能,Crawl4AI都能帮您简化工作流程。它可以直接在Python项目中使用,或者将其集成到REST API中,实现快速、稳定的数据爬取和处理。这样,无论是数据的实时获取还是后续的分析处理,都能更加得心应手。

1.快速使用

以下是个简单的例子,展示了Crawl4AI强大的异步能力:

import asyncio
from crawl4ai import AsyncWebCrawlerasyncdef main():# 初始化异步网页爬虫asyncwith AsyncWebCrawler(verbose=True) as crawler:# 爬取指定的 URLresult = 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函数。

2.特性亮点

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3.安装指南

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

3.1 基本安装(推荐)

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

pip install crawl4ai

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

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

playwright install

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

python -m playwright install chromium

3.2 同步版本安装

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

pip install crawl4ai[sync]

3.3 开发者安装

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

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

4.高级应用

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

4.1 执行JavaScript和使用CSS选择器

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

import asyncio
from crawl4ai import AsyncWebCrawlerasyncdef 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())

4.2 使用代理

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

import asyncio
from crawl4ai import AsyncWebCrawlerasync 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())

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

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

import asyncio
import json
from crawl4ai import AsyncWebCrawler
from crawl4ai.extraction_strategy import JsonCssExtractionStrategyasyncdef 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())

4.4 使用 OpenAI 提取结构化数据

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

import os
import asyncio
from crawl4ai import AsyncWebCrawler
from crawl4ai.extraction_strategy import LLMExtractionStrategy
from pydantic import BaseModel, Fieldclass 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())

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

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

import asyncio
import re
from bs4 import BeautifulSoup
from crawl4ai import AsyncWebCrawlerasyncdef 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 = commitbreakawait 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 pagesresult = 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())

5.性能对比

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

要点总结:

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

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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/web/74727.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

从零开始玩python--python版植物大战僵尸来袭

大家好呀,小伙伴们!今天要给大家介绍一个超有趣的Python项目 - 用pygame制作植物大战僵尸游戏的进阶版本。相信不少小伙伴都玩过这款经典游戏,今天我们就用Python来实现它,让编程学习变得更加有趣!🌟 一、…

图解AUTOSAR_SWS_FlashTest

AUTOSAR Flash Test模块详解 基于AUTOSAR 4.4.0规范的Flash测试模块分析与图解 目录 概述 1.1 Flash Test模块的作用 1.2 工作原理架构设计 2.1 整体架构 2.2 依赖关系状态管理 3.1 状态转换图 3.2 前台与后台测试模式配置结构 4.1 配置类图 4.2 关键配置参数交互流程 5.1 序列…

【mongodb】mongodb的字段类型

目录 1. 基本数据类型1.1 String1.2 Number1.3 Boolean1.4 Date1.5 Null1.6 ObjectId1.7 Array1.8 Binary Data1.9 Object 2. 特殊数据类型2.1 Regular Expression2.2 JavaScript2.3 Symbol2.4 Decimal1282.5 Timestamp2.6 MinKey/MaxKey2.7 DBPointer 3. 常用字段类型示例4. 注…

MySQL篇(五)MySQL主从同步原理深度剖析

MySQL篇(五)MySQL主从同步原理深度剖析 MySQL篇(五)MySQL主从同步原理深度剖析一、引言二、MySQL主从同步基础概念主库(Master)从库(Slave)二进制日志(Binary Log&#x…

论文学习16:Learning Transferable Visual Models From Natural Language Supervision

代码来源 Learning Transferable Visual Models From Natural Language Supervisionhttps://arxiv.org/pdf/2103.00020 模块作用 当前最先进的计算机视觉系统被训练用于预测一组固定的、预先定义的目标类别。这种受限的监督方式限制了它们的通用性和可用性,因为要…

[MySQL初阶]MySQL(9)事务机制

标题:[MySQL初阶]MySQL(9)事物机制 水墨不写bug 文章目录 一、认识事务1、多线程访问数据库出现的问题2、对CURD的限制是通过事务机制实现的3、事务的四个属性4、哪些引擎支持事务 二、事务的提交与autocommit设置三、事务的隔离性和隔离级别…

spring-cloud-alibaba-nacos-config使用说明

一、核心功能与定位 Spring Cloud Alibaba Nacos Config 是 Spring Cloud Alibaba 生态中的核心组件之一,专为微服务架构提供动态配置管理能力。它通过整合 Nacos 的配置中心功能,替代传统的 Spring Cloud Config,提供更高效的配置集中化管理…

SonarQube数据库配置

SonarQube部署完成后,在浏览器地址栏输入http://IP:9000可以进入登录页面,以本机运行为例,地址为http://127.0.0.1:9000/,默认登录名:admin,登录密码也是admin。登录后会要求设置密码: 按要求设…

医药档案区块链系统

1. 医生用户模块​​ ​​目标用户​​:医护人员 ​​核心功能​​: ​​检索档案​​:通过关键词或筛选条件快速定位患者健康档案。​​请求授权​​:向个人用户发起档案访问权限申请,需经对方确认。​​查看档案​…

CSS3学习教程,从入门到精通, 化妆品网站 HTML5 + CSS3 完整项目(26)

化妆品网站 HTML5 CSS3 完整项目 下面是一个完整的化妆品网站项目,包含主页、登录页面和注册页面。我将按照您的要求提供详细的代码和注释。 1. 网站规划与需求分析 需求分析 展示化妆品产品信息提供用户注册和登录功能响应式设计,适配不同设备美观…

ROS2 多机时间同步(Chrony配置简明指南)

适用场景: 主机运行 ROS2 Humble(发布 /scan 等),板子运行 ROS2 Foxy(发布 /tf 等),两边通过 ROS_DOMAIN_ID 跨平台通讯。需要保证系统时间对齐,避免 TF 插值失败、建图抖动等问题。…

Nginx配置伪静态,URL重写

Nginx配置伪静态,URL重写 [ Nginx ] 在Nginx低版本中,是不支持PATHINFO的,但是可以通过在Nginx.conf中配置转发规则实现: location / { // …..省略部分代码if (!-e $request_filename) {rewrite ^(.*)$ /index.php?s/$1 l…

电路笔记(元器件):ADC LTC系列模数转换器的输出范围+满量程和偏移调整

LTC1740(LTC1740官方文档)是Analog Devices(原Linear Technology)公司生产的一款高性能、低功耗的14位模数转换器(ADC)。它通常用于需要高精度和快速采样率的应用中,如通信系统、数据采集设备等。同类产品 LTC1746:一款14位、40Ms…

续-算法-数学知识

3、欧拉函数 1、定义: 1~n 中与 n 互质的数的个数 例如:6 的有 1 2 3 4 5 6 其中,与 n 互质 的 数的个数为 2个分别是:1、5 2、计算: $ N p_1^{a1} p_2^{a2} p_3^{a3} … p_k^{ak} $(例如&#x…

C/C++测试框架googletest使用示例

文章目录 文档编译安装示例参考文章 文档 https://github.com/google/googletest https://google.github.io/googletest/ 编译安装 googletest是cmake项目,可以用cmake指令编译 cmake -B build && cmake --build build将编译产物lib和include 两个文件夹…

LintCode第974题-求矩阵各节点的最短路径(以0为标准)

描述 给定一个由0和1组成的矩阵,求每个单元格最近的0的距离。 两个相邻细胞之间的距离是1。 给定矩阵的元素数不超过10,000。 在给定的矩阵中至少有一个0。 单元格在四个方向上相邻:上,下,左和右。 样例 例1: 输入: [[0,0,0],[0,0,0],[0…

Redis核心机制-缓存、分布式锁

目录 缓存 缓存更新策略 定期生成 实时生成 缓存问题 缓存预热(Cache preheating) 缓存穿透(Cache penetration) 缓存雪崩(Cache avalanche) 缓存击穿(Cache breakdown) 分…

CF每日5题(1300-1500)

最近急速补练蓝桥杯中,疏于cf练习。 感觉自己过题还是太慢了。 今日水题,我水水水水。 1- 1979C lcm 水 1400 第 i i i局赢了,1个硬币顶 k [ i ] k[i] k[i]个贡献,所以每局分硬币 x i 1 k [ i ] x_i{1\over k[i]} xi​k[i]1​个…

从代码学习深度学习 - LSTM PyTorch版

文章目录 前言一、数据加载与预处理1.1 代码实现1.2 功能解析二、LSTM介绍2.1 LSTM原理2.2 模型定义代码解析三、训练与预测3.1 训练逻辑代码解析3.2 可视化工具功能解析功能结果总结前言 深度学习中的循环神经网络(RNN)及其变种长短期记忆网络(LSTM)在处理序列数据(如文…

easy-poi 一对多导出

1. 需求: 某一列上下两行单元格A,B值一样且这两个单元格, 前面所有列对应单元格值一样的话, 就对A,B 两个单元格进行纵向合并单元格 1. 核心思路: 先对数据集的国家,省份,城市...... id 身份证进行排序…