Crawl4AI は、非同期 Web クローリングとデータ抽出を簡素化し、大規模言語モデル (LLM) や AI アプリケーションからアクセスできるようにします。 ?
CrawlResult
内でのファイルのクロール、ダウンロード、追跡を統合しました。srcset
、 picture
、およびレスポンシブ画像形式をサポートします。file://
パスと生の HTML ( raw:
) を直接クロールします。これを使って遊んでみましょう
ドキュメント Web サイトにアクセスしてください
Crawl4AI は、さまざまな使用例に合わせて柔軟なインストール オプションを提供します。 Python パッケージとしてインストールすることも、Docker を使用することもできます。
ニーズに最適なインストール オプションを選択してください。
基本的な Web クローリングおよびスクレイピング タスクの場合:
pip install crawl4ai
デフォルトでは、Web クローリングに Playwright を使用して、Crawl4AI の非同期バージョンがインストールされます。
注: Crawl4AI をインストールすると、セットアップ スクリプトによって Playwright が自動的にインストールされ、セットアップされます。ただし、Playwright 関連のエラーが発生した場合は、次のいずれかの方法を使用して手動でインストールできます。
コマンドライン経由:
playwright install
上記が機能しない場合は、次のより具体的なコマンドを試してください。
python -m playwright install chromium
この 2 番目の方法は、場合によってはより信頼性が高いことが証明されています。
Selenium を使用した同期バージョンが必要な場合:
pip install crawl4ai[sync]
ソース コードの変更を計画している寄稿者向け:
git clone https://github.com/unclecode/crawl4ai.git
cd crawl4ai
pip install -e .
ワンクリックで Crawl4AI の独自のインスタンスをデプロイします。
推奨スペック: 4GB以上のRAM。安定した動作を実現するために、導入時には「professional-xs」以上を選択してください。
デプロイでは次のことが行われます。
Crawl4AI は、簡単にデプロイできるように Docker イメージとして利用できます。 Docker Hub から直接プルするか (推奨)、リポジトリからビルドすることができます。
# Pull and run from Docker Hub (choose one):
docker pull unclecode/crawl4ai:basic # Basic crawling features
docker pull unclecode/crawl4ai:all # Full installation (ML, LLM support)
docker pull unclecode/crawl4ai:gpu # GPU-enabled version
# Run the container
docker run -p 11235:11235 unclecode/crawl4ai:basic # Replace 'basic' with your chosen version
# In case you want to set platform to arm64
docker run --platform linux/arm64 -p 11235:11235 unclecode/crawl4ai:basic
# In case to allocate more shared memory for the container
docker run --shm-size=2gb -p 11235:11235 unclecode/crawl4ai:basic
# Clone the repository
git clone https://github.com/unclecode/crawl4ai.git
cd crawl4ai
# Build the image
docker build -t crawl4ai:local
--build-arg INSTALL_TYPE=basic # Options: basic, all
.
# In case you want to set platform to arm64
docker build -t crawl4ai:local
--build-arg INSTALL_TYPE=basic # Options: basic, all
--platform linux/arm64
.
# Run your local build
docker run -p 11235:11235 crawl4ai:local
クイック テスト (両方のオプションで機能します):
import requests
# Submit a crawl job
response = requests . post (
"http://localhost:11235/crawl" ,
json = { "urls" : "https://example.com" , "priority" : 10 }
)
task_id = response . json ()[ "task_id" ]
# Get results
result = requests . get ( f"http://localhost:11235/task/ { task_id } " )
高度な構成、環境変数、使用例については、Docker デプロイメント ガイドを参照してください。
import asyncio
from crawl4ai import AsyncWebCrawler
async def main ():
async with AsyncWebCrawler ( verbose = True ) as crawler :
result = await crawler . arun ( url = "https://www.nbcnews.com/business" )
print ( result . markdown )
if __name__ == "__main__" :
asyncio . run ( main ())
import asyncio
from crawl4ai import AsyncWebCrawler
async def main ():
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 ,
css_selector = ".wide-tease-item__description" ,
bypass_cache = True
)
print ( result . extracted_content )
if __name__ == "__main__" :
asyncio . run ( main ())
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 ())
JsonCssExtractionStrategy
使用すると、CSS セレクターを使用して Web ページから構造化データを正確に抽出できます。
import asyncio
import json
from crawl4ai import AsyncWebCrawler
from crawl4ai . extraction_strategy import JsonCssExtractionStrategy
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 ))
if __name__ == "__main__" :
asyncio . run ( extract_news_teasers ())
より高度な使用例については、ドキュメントの「例」セクションを参照してください。
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." )
async def main ():
async with 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-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 )
if __name__ == "__main__" :
asyncio . run ( main ())
Crawl4AI は、JavaScript 経由で読み込まれた動的コンテンツを含む複数のページをクロールするなど、複雑なシナリオの処理に優れています。複数のページにわたって GitHub コミットをクロールする例を次に示します。
import asyncio
import re
from bs4 import BeautifulSoup
from crawl4ai import AsyncWebCrawler
async def crawl_typescript_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/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 > 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" )
if __name__ == "__main__" :
asyncio . run ( crawl_typescript_commits ())
この例は、コンテンツが非同期で読み込まれる複雑なシナリオを処理する Crawl4AI の機能を示しています。 GitHub コミットの複数のページをクロールし、JavaScript を実行して新しいコンテンツをロードし、カスタム フックを使用してデータがロードされていることを確認してから続行します。
より高度な使用例については、ドキュメントの「例」セクションを参照してください。
Crawl4AI はスピードを主な焦点として設計されています。私たちの目標は、高品質のデータ抽出により可能な限り最速の応答を提供し、データとユーザーの間の抽象化を最小限に抑えることです。
Crawl4AI と有料サービス Firecrawl の速度比較を実施しました。結果は、Crawl4AI の優れたパフォーマンスを示しています。
Firecrawl:
Time taken: 7.02 seconds
Content length: 42074 characters
Images found: 49
Crawl4AI (simple crawl):
Time taken: 1.60 seconds
Content length: 18238 characters
Images found: 49
Crawl4AI (with JavaScript execution):
Time taken: 4.64 seconds
Content length: 40869 characters
Images found: 89
ご覧のとおり、Crawl4AI は Firecrawl を大幅に上回っています。
完全な比較コードは、リポジトリdocs/examples/crawl4ai_vs_firecrawl.py
にあります。
インストール手順、高度な機能、API リファレンスなどの詳細なドキュメントについては、ドキュメント Web サイトを参照してください。
開発計画と今後の機能の詳細については、ロードマップをご覧ください。
オープンソース コミュニティからの貢献を歓迎します。詳細については、貢献ガイドラインをご覧ください。
Crawl4AI は、Apache 2.0 ライセンスに基づいてリリースされています。
ご質問、ご提案、フィードバックがございましたら、お気軽にお問い合わせください。
ハッピークロール! ⁉️
私たちの使命は、デジタル時代における個人データと企業データの未開発の可能性を解き放つことです。今日の世界では、個人や組織が膨大な量の貴重なデジタル フットプリントを生成していますが、このデータは真の資産としてほとんど活用されていないままです。
当社のオープンソース ソリューションは、開発者やイノベーターがデータの抽出と構造化のためのツールを構築できるようにし、データ所有権の新時代の基礎を築きます。個人データと企業データを構造化された取引可能な資産に変換することで、個人がデジタル フットプリントを活用し、組織が集合知識の価値を引き出す機会を創出します。
このデータの民主化は、データ共有エコノミーへの第一歩を表しており、データ共有への積極的な参加が AI の進歩を促進すると同時に、そのメリットがデータ作成者に確実に還元されるようになります。このアプローチを通じて、私たちは AI 開発が合成代替品ではなく本物の人間の知識に基づいて行われる未来を構築しています。
当社のビジョン、機会、今後の道筋について詳しくは、当社のミッション ステートメント全文をご覧ください。
当社のビジョン、課題、ソリューションの詳細については、当社のミッション ステートメント全文をご覧ください。