点击上方蓝字关注我们
Crawl4AI是一款专为大型语言模型(LLMs)和AI应用设计的开源网页爬虫和数据提取工具。最近挺火的开源AI网络爬虫工具:Crawl4AI 可以直接用于大语言模型和AI应用。性能超快,还能输出适合大语言模型的格式,比如JSON、清理过的HTML和markdown。它还支持同时爬取多个网址,能提取所有媒体标签(图片、音频、视频),以及所有内外部链接。可以自定义用户代理,还能给网页截图,甚至在爬取之前执行自定义JavaScript。
一、概述
Crawl4AI旨在简化网页数据的抓取和提取过程,为数据科学家、研究人员、开发人员和AI应用开发者提供高效、便捷的数据获取解决方案。它针对LLM的训练和应用场景进行了优化,能够高效地从各类网站中提取高质量数据,为LLM提供丰富且优质的训练素材。
二、核心优势
开源免费:Crawl4AI是一款完全免费且开源的工具,用户可以自由地使用、修改和分发。
LLM友好:支持LLM友好的输出格式,如JSON、清洁的HTML和Markdown,方便用户进行后续的数据处理和模型训练。
多URL支持:同时支持爬取多个URL,提高数据抓取的效率。
高级提取策略:提供多种高级提取策略,如余弦聚类、LLM等,帮助用户更精确地提取所需数据。
丰富功能:支持提取并返回所有媒体标签(图片、音频和视频),提取所有外部和内部链接,从页面提取元数据等。
灵活配置:提供自定义钩子用于认证、头部和爬取前的页面修改,用户代理自定义,截取页面屏幕截图,执行多个自定义JavaScript脚本等功能,满足用户多样化的需求。
三、应用场景
Crawl4AI适用于需要从网页中快速提取大量数据的场景,如:
数据科学研究:为数据科学家提供丰富的数据源,支持其进行数据分析、挖掘和建模。
AI模型训练:为AI应用开发者提供高质量的训练数据,助力其提升模型的性能和准确性。
网络数据挖掘:帮助研究人员从大量网页中挖掘有价值的信息,支持其进行学术研究。
四、使用指南
Crawl4AI提供了详细的官方文档和安装指南,用户可以通过以下方式获取和使用:
访问官方网站:前往Crawl4AI官方网站或官方文档网站,了解工具的详细介绍和使用方法。
安装工具:用户可以通过pip安装Crawl4AI,也可以使用Docker容器来简化设置。在安装过程中,如果遇到与Playwright相关的错误,可以尝试手动安装Playwright。
编写爬虫代码:根据官方文档提供的示例代码和API文档,编写符合自己需求的爬虫代码。
运行爬虫:执行编写好的爬虫代码,开始从网页中提取数据。
五、步骤示例
第 1 步:安装和设置
pip install “crawl4ai @ git+https://github.com/unclecode/crawl4ai.git"
第 2 步:数据提取
from crawl4ai import WebCrawler
# Create an instance of WebCrawler
crawler = WebCrawler()
# Warm up the crawler (load necessary models)
crawler.warmup()
# Run the crawler on a URL
result = crawler.run(url="https://openai.com/api/pricing/")
# Print the extracted content
print(result.markdown)
第 3 步:使用 LLM
使用 LLM (Large Language Model) 定义提取策略,并将提取的数据转换为结构化格式:
import os
from crawl4ai import WebCrawler
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.")
url = 'https://openai.com/api/pricing/'
crawler = WebCrawler()
crawler.warmup()
result = crawler.run(
url=url,
word_count_threshold=1,
extraction_strategy= LLMExtractionStrategy(
provider= "openai/gpt-4o", 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)
第 4 步:与 AI 智能体集成
将 Crawl 与 Praison CrewAI 代理集成以实现高效的数据处理:
pip install praisonai
创建一个工具文件 (tools.py) 以封装 Crawl 工具:
# tools.py
import os
from crawl4ai import WebCrawler
from crawl4ai.extraction_strategy import LLMExtractionStrategy
from pydantic import BaseModel, Field
from praisonai_tools import BaseTool
class ModelFee(BaseModel):
llm_model_name: str = Field(..., description="Name of the model.")
input_fee: str = Field(..., description="Fee for input token for the model.")
output_fee: str = Field(..., description="Fee for output token for the model.")
class ModelFeeTool(BaseTool):
name: str = "ModelFeeTool"
description: str = "Extracts model fees for input and output tokens from the given pricing page."
def _run(self, url: str):
crawler = WebCrawler()
crawler.warmup()
result = crawler.run(
url=url,
word_count_threshold=1,
extraction_strategy= LLMExtractionStrategy(
provider="openai/gpt-4o",
api_token=os.getenv('OPENAI_API_KEY'),
schema=ModelFee.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,
)
return result.extracted_content
if __name__ == "__main__":
# Test the ModelFeeTool
tool = ModelFeeTool()
url = "https://www.openai.com/pricing"
result = tool.run(url)
print(result)
将 AI 代理配置为使用 Crawl 工具进行 Web 抓取和数据提取:
framework: crewai
topic: extract model pricing from websites
roles:
web_scraper:
backstory: An expert in web scraping with a deep understanding of extracting structured
data from online sources. https://openai.com/api/pricing/ https://www.anthropic.com/pricing https://cohere.com/pricing
goal: Gather model pricing data from various websites
role: Web Scraper
tasks:
scrape_model_pricing:
description: Scrape model pricing information from the provided list of websites.
expected_output: Raw HTML or JSON containing model pricing data.
tools:
- 'ModelFeeTool'
data_cleaner:
backstory: Specialist in data cleaning, ensuring that all collected data is accurate
and properly formatted.
goal: Clean and organize the scraped pricing data
role: Data Cleaner
tasks:
clean_pricing_data:
description: Process the raw scraped data to remove any duplicates and inconsistencies,
and convert it into a structured format.
expected_output: Cleaned and organized JSON or CSV file with model pricing
data.
tools:
- ''
data_analyzer:
backstory: Data analysis expert focused on deriving actionable insights from structured
data.
goal: Analyze the cleaned pricing data to extract insights
role: Data Analyzer
tasks:
analyze_pricing_data:
description: Analyze the cleaned data to extract trends, patterns, and insights
on model pricing.
expected_output: Detailed report summarizing model pricing trends and insights.
tools:
- ''
dependencies: []
Crawl 是一个强大的工具,它使 AI 代理能够更高效、更准确地执行 Web 爬虫和数据提取任务。