> ## Content Index
> Fetch the complete content index at: https://www.hubwiz.com/blog/llms.txt
> Use this file to discover other available public pages before exploring further.

# Crawl4AI数据集制作必备爬虫库
- URL: https://www.hubwiz.com/blog/crawl4ai-essential-cralwer-library-for-building-datasets/
- Published: 2024-11-09T02:51:52.000Z
- Updated: 2024-11-09T03:11:22.000Z
- Description: Crawl4AI 是一个创新的开源 Python 库，旨在简化网络爬虫和数据提取，使其成为开发人员和人工智能爱好者的必备工具。
- Author: admin
- Tags: LIBRARY, DATASET, WEB SCRAPER, CRAWL4AI, LLM, #Import 2026-10-14 14:41

在当今数据驱动的世界中，高效收集和处理信息的能力对于人工智能 (AI) 应用程序的成功至关重要。随着人工智能的不断发展，对用于训练大型语言模型 (LLM) 的结构化数据的需求从未如此高涨。

[Crawl4AI ](https://github.com/unclecode/crawl4ai?ref=hubwiz.com)是一个创新的开源 Python 库，旨在简化网络爬虫和数据提取，使其成为开发人员和人工智能爱好者的必备工具。本博客将探讨 Crawl4AI 的特性、功能和用例，重点介绍它如何帮助用户利用网络的力量进行人工智能训练。

## 1、Crawl4AI简介

Crawl4AI 是一个开源网络爬虫和抓取框架，旨在自动从网站收集数据。它允许用户同时抓取多个 URL，使其成为需要大规模数据收集的项目的理想选择。凭借针对人工智能应用程序量身定制的功能，Crawl4AI 简化了将原始网络数据转换为结构化格式的过程。

Crawl4AI 的主要特点：

- 开源。其开源特性确保用户可以完全访问代码，从而实现自定义和可扩展性。此外，强大的社区支持和丰富的文档使新用户更容易上手。
- 超快的性能。Crawl4AI 的突出特点之一是其非凡的速度。该框架经过优化，性能优于许多付费服务，使用户能够快速高效地提取数据。
- 异步架构。支持并发抓取多个 URL，大大减少了大规模数据收集所需的时间。
- LLM 友好的输出格式。支持各种输出格式，包括 JSON、清理的 HTML 和 Markdown，确保轻松集成到 AI 模型中。
- 提取并返回所有媒体标签。使用 Crawl4AI，用户可以提取各种媒体类型，包括图像、音频和视频。此功能对于依赖多媒体内容的应用程序（例如社交媒体分析或内容创建）特别有用。
- JavaScript 执行。允许抓取动态内容，确保其他抓取工具可能错过的全面数据收集。
- 各种分块策略。Crawl4AI 支持多种分块策略，例如基于主题、正则表达式和基于句子的分块。这种灵活性允许用户根据特定要求定制数据提取，确保为各种应用程序提供最佳结果。
- 高级提取技术。利用 XPath 和正则表达式等强大的方法，让用户能够从网页中精确定位所需的数据。
- 元数据提取。收集主要内容以及必要的元数据，丰富 AI 训练的数据集。
- 自定义钩子和用户代理支持。用户可以为身份验证和标头定义自定义钩子，以及为 HTTP 请求自定义用户代理，从而更好地控制抓取过程。
- 错误处理和重试机制。结合强大的错误处理和重试策略，即使遇到网络问题或页面加载失败也能确保数据完整性。
- 速率限制和节流。有助于避免目标服务器不堪重负，并确保符合网络抓取最佳实践。

Crawl4AI 不仅仅是一个网络抓取工具；它是一个用于高级异步网络抓取和数据提取的综合解决方案，专为满足开发人员和数据分析师的需求而设计。

现在，我们将深入研究 Crawl4AI 的一些核心特性和功能，展示代码示例以说明如何实现这些特性和功能以优化网络数据提取。

## 2、安装Crawl4AI

有几种安装 Crawl4AI 的选项 - 你可以将其安装为 Python 包，使用 Docker 设置它，或者在本地运行它。以下是 Python 包安装步骤：

```
# To install all available features
!pip3 install "crawl4ai[all]"

# After installation, download the necessary models for better performance:
!crawl4ai-download-models

# Lastly, install Playwright dependencies
!playwright install 
```

有关不同的安装方法，请参阅[此处](https://crawl4ai.com/mkdocs/installation/?ref=hubwiz.com) 。

## 3、Crawl4AI基本用法

要开始使用 Crawl4AI，我们首先需要创建一个 `AsyncWebCrawler` 实例。这是核心组件，它将使用异步上下文管理器有效地管理抓取生命周期。默认情况下，它将缓存抓取结果，这意味着对同一 URL 的后续抓取将更快！！

```
from crawl4ai import AsyncWebCrawler
from crawl4ai.chunking_strategy import RegexChunking

async with AsyncWebCrawler(verbose=True) as crawler:
    result = await crawler.arun(url="https://en.wikipedia.org/wiki/3_Idiots", bypass_cache=False) 
    print(f"Extracted content: {result.extracted_content}")
```

![](https://www.hubwiz.com/blog/content/images/2024/11/image-703.png)

高执行速度

在上面的代码片段中：

- `url`：指定要抓取的网页。
- `bypass_cache`：是否强制进行全新抓取

提取的内容有多种格式，如 `markdown` 和 `cleaned_html`，可根据你的需求提供灵活性。

```
print(result.markdown)
print(result.cleaned_html)
```

## 4、Crawl4AI截屏

Crawl4AI还允许你捕获正在抓取的页面的屏幕截图。

```
import base64
from crawl4ai import AsyncWebCrawler

async with AsyncWebCrawler(verbose=True) as crawler:
    result = await crawler.arun(url="https://www.cricbuzz.com/", screenshot=True)
    with open("cricbuzz_screenshot.png", "wb") as f:
        f.write(base64.b64decode(result.screenshot))
    print("Screenshot saved to 'screenshot.png'!")
```

## 5、为Crawl4AI添加分块策略

现在我们将根据给定的正则表达式模式拆分文本。

- `word_count_threshold`：设置有意义的内容块的最小字数。
- `chunking_strategy`：定义用于拆分文本的分块策略

```
from crawl4ai import AsyncWebCrawler
from crawl4ai.chunking_strategy import RegexChunking

async with AsyncWebCrawler(verbose=True) as crawler:
    result = await crawler.arun(url="https://en.wikipedia.org/wiki/3_Idiots", chunking_strategy=RegexChunking(patterns=["\n\n"]), word_count_threshold=10) 
    print(f"Extracted content: {result.extracted_content}")
```

## 6、为Crawl4AI添加高级提取策略

现在，让我们在爬取中添加一个智能提取策略 — `JsonCssExtractionStrategy`。

`JsonCssExtractionStrategy` 通过定义具有基本选择器的架构来实现精确的结构化数据提取，这些选择器用于页面上的重复元素。架构中的每个字段都有自己的选择器，允许提取嵌套结构或列表。此方法非常适合将 Web 内容（如产品列表、文章或搜索结果）转换为干净的 JSON 格式，从而为 Web 数据提取提供灵活性和准确性。

```
from crawl4ai import AsyncWebCrawler
from crawl4ai.extraction_strategy import JsonCssExtractionStrategy
import json
import nest_asyncio
nest_asyncio.apply()

async def 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)

    async with 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))

await extract_news_teasers()
```

## 7、Crawl4AI基于会话的动态内容抓取

Crawl4AI 基于会话的抓取在处理 GitHub 等平台上的动态内容时特别有用。在此示例中，我们使用它来提取多个页面的提交历史记录，并利用自定义钩子确保正确加载新内容。

```
import asyncio
import re
from bs4 import BeautifulSoup
from crawl4ai import AsyncWebCrawler

async def crawl_linux_commits():
    first_commit = ""
    async def on_execution_started(page):
        nonlocal first_commit 
        try:
            while True:
                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}")

    async with AsyncWebCrawler(verbose=True) as crawler:
        crawler.crawler_strategy.set_hook('on_execution_started', on_execution_started)

        url = "https://github.com/torvalds/linux/commits/master"
        session_id = "linux_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 > 0 else None,
                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")
            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")

asyncio.run(crawl_linux_commits())
```

- 基于会话的抓取：我们维护一个会话来处理动态内容并加载新页面。
- JavaScript 执行：自定义 JavaScript 单击 GitHub 提交页面上的“下一步”按钮以加载更多提交。
- 自定义钩子： `on_execution_started` 钩子确保在继续之前加载新提交。  
此技术允许您从动态页面中提取内容，同时管理跨多个请求的状态。

有关更多详细信息和高级用法，请查看[完整文档](https://crawl4ai.com/mkdocs/?ref=hubwiz.com)。

## 8、Crawl4AI的实际应用

Crawl4AI 适用于广泛的应用，包括：

- 训练大型语言模型：Crawl4AI 收集的结构化数据非常适合训练 LLM，有助于提高其在各种应用程序中的性能。
- 市场研究：企业可以利用 Crawl4AI 从竞争对手的网站、新闻文章和社交媒体中收集见解，从而实现数据驱动的决策。
- 内容聚合：内容创建者可以使用 Crawl4AI 从多个来源收集和整理信息，从而简化内容创建过程。
- 学术研究：研究人员可以自动从学术出版物和在线数据库收集数据，从而促进文献综述和数据分析。
- 情绪分析：通过抓取评论和社交媒体帖子，用户可以分析公众对产品或服务的情绪。
- 实时数据检索：RAG 系统可以利用 Crawl4AI 从网络上获取最新信息，从而提高 AI 生成内容的准确性。
- 动态函数调用：AI 代理可以利用 Crawl4AI 根据实时数据执行函数调用，从而实现更具交互性和响应性的应用程序。

## 9、结束语

随着数据在各个行业的决策过程中变得越来越不可或缺，Crawl4AI 等工具对于利用网络数据至关重要。其强大的自动化功能不仅可以节省时间，还可以为分析和洞察生成开辟新的途径。 Crawl4AI 是一款功能强大且高效的网页抓取工具，具有多 URL 抓取、媒体提取和高级输出格式等功能，可满足现代数据收集需求。无论您是开发人员、研究人员还是企业主，它都能提供必要的资源来简化数据提取流程并最大限度地发挥洞察的价值。

---

原文链接：[Crawl4AI: Unleashing Efficient Web Scraping](https://gautam75.medium.com/crawl4ai-unleashing-efficient-web-scraping-1825560300c3?ref=hubwiz.com)

汇智网翻译整理，转载请标明出处