官方鏈接:
Github :https://github.com/unclecode/crawl4ai
文檔主頁:https://docs.crawl4ai.com/
當前版本:Crawl4AI v0.5.0
主要新功能:
- 可配置策略(廣度優先、深度優先、最佳優先)探索整個網站。
- 根據可用內存動態調整并發性。
- 可 Docker 部署
- 有命令行界面 (CLI)
- LLM配置 (LLMConfig):方便 LLM模型用于提取、過濾和模式生成。
次要更新和改進:
- LXML爬取模式:使用LXMLWebScrapingStrategy進行更快的HTML解析。
- 代理輪換:添加了ProxyRotationStrategy,并實現了RoundRobinProxyStrategy。
- PDF處理:從PDF文件中提取文本、圖像和元數據。
- URL重定向跟蹤:自動跟蹤并記錄重定向。
- 遵守Robots.txt:可選擇性地遵守網站爬取規則。
- LLM驅動的模式生成:使用LLM自動創建提取模式。
- LLMContentFilter:使用LLM生成高質量、重點突出的markdown。
- 改進的錯誤處理和穩定性:眾多錯誤修復和性能增強。
- 增強文檔:更新指南和示例。
安裝 Crawl4AI
系統環境:
- Windows 11 Professional? 與 Ubuntu24
- Python 3.12
安裝過程:
1. 基礎安裝
在 Windows 11 CMD?
pip install crawl4ai
在 Ubuntu24?中運行:
python3 -m venv -venv
source venv/bin/activate
pip install crawl4ai
安裝核心庫與基本依賴內容,不包含任何高級功能。
裝了一堆:
2. 自動設置
crawl4ai-setup
自動完成瀏覽器安裝、系統兼容性檢查和環境驗證:
Ubuntu 24:
Windows 11:
3. 校驗安裝
import asyncio
from crawl4ai import AsyncWebCrawler, BrowserConfig, CrawlerRunConfigasync def main():async with AsyncWebCrawler() as crawler:result = await crawler.arun(url="https://www.google.com",)print(result.markdown[:300]) # Show the first 300 characters of extracted textif __name__ == "__main__":asyncio.run(main())
正常是:
4. 安裝診斷命令
crawl4ai-doctor
使用 Crawl4AI
基本的 CLI 方式:
1. 指定格式輸出,參數:-o 或 --output [all|json|markdown|md|markdown-fit|md-fit]
crwl https://docs.crawl4ai.com/ -o markdown
2. 不使用已經存在的緩存,從服務器獲取最新內容,參數: -b?,?--bypass-cache
crwl https://docs.crawl4ai.com/ --bypass-cache
crwl https://docs.crawl4ai.com/ -b
3. 帶有詳細的運行信息和日志, 參數: -v, --verbose
詳細信息:
- 爬取的每個步驟
- 請求和響應的詳情
- 遇到的問題或警告
- 處理過程中的狀態變化
- 性能相關的信息(如加載時間)
對于調試問題或了解程序的工作方式特別有用。如網站爬取失敗或結果不符合預期,verbose 模式可以幫助你確定問題出在哪里。
crwl https://docs.crawl4ai.com/ -v
crwl https://docs.crawl4ai.com/ --verbose
4. 指定提取策略的文件?參數: -e,?--extraction-config [PATH]
crwl https://docs.crawl4ai.com/ -e [策略文件路徑]
crwl https://docs.crawl4ai.com/ --extraction-config [策略文件路徑]
自定義爬蟲如何從網頁中提取內容的詳細規則和策略,可以精確控制數據提取,使用YAML或JSON格式結構。
1) 提取策略配置文件的主要功能
- 指定使用哪種類型的選擇器(CSS、XPath、正則表達式等)來定位頁面元素
- 定義如何處理和轉換提取的原始內容
- 刪除多余空格、HTML標簽
- 將價格文本轉為數字
- 內容分割和合并
- 支持嵌套數據結構的提取
- 先定位父元素,再從父元素中提取子元素
- 處理列表、表格等復雜結構
- 指定條件,決定是否提取內容
- 如:只提取含有特定關鍵詞的段落
- 定義在多頁面間導航以提取內容
- 分頁處理
2) 例:從Amazon產品頁面提取DEWALT電動工具的各種信息
主要提取內容
- 基本信息:標題、品牌、型號、ASIN
- 價格信息:當前價格、原價、優惠狀態
- 產品圖片:主圖及所有備選圖片
- 技術規格:電壓、扭矩、重量、尺寸等
- 產品特點:所有列出的產品特性
- 評論數據:平均評分和評論數量
- 可用性:庫存狀態和配送選項
- 分類信息:主類別和面包屑導航中的子類別
- 相關產品:經常一起購買的商品
文件名:C:\temp\dewalt-extraction-strategy.yaml
extraction_strategies:# Basic product information- name: "product_title"selector_type: "css"selector: "#productTitle"attribute: "text"transform: "trim"target_field: "productBasicInfo.title"- name: "product_brand"selector_type: "css"selector: "#bylineInfo"attribute: "text"transforms: - "trim"- "regex_replace:Brand: (.*)|Visit the (.*) Store|(.*) Store|$1$2$3"target_field: "productBasicInfo.brand"- name: "product_model"selector_type: "css"selector: "tr.po-model_name td.po-model_name"attribute: "text"transform: "trim"target_field: "productBasicInfo.model"- name: "product_asin"selector_type: "css"selector: "tr:contains('ASIN') td.a-span9"attribute: "text"transform: "trim"target_field: "productBasicInfo.asin"# Price information- name: "current_price"selector_type: "css"selector: ".priceToPay .a-offscreen"attribute: "text"transforms:- "trim"- "regex_replace:\\$(.*)$|$1"- "to_number"target_field: "pricing.currentPrice"- name: "original_price"selector_type: "css"selector: ".basisPrice .a-offscreen"attribute: "text"transforms:- "trim"- "regex_replace:\\$(.*)$|$1"- "to_number"target_field: "pricing.originalPrice"- name: "deal_badge"selector_type: "css"selector: "#dealBadge"exists_as: "dealAvailable"target_field: "pricing.dealAvailable"# Images- name: "product_images"selector_type: "css"selector: "#landingImage"attribute: "data-old-hires"target_field: "images"is_list: true- name: "alternate_images"selector_type: "css"selector: "#altImages .item img"attribute: "src"transforms:- "regex_replace:(.*)\\._.*\\.jpg$|$1.jpg"target_field: "images"append: trueis_list: true# Technical details- name: "voltage"selector_type: "css"selector: "tr:contains('Voltage') td.a-span9"attribute: "text"transform: "trim"target_field: "technicalDetails.voltage"- name: "torque"selector_type: "css"selector: "tr:contains('Torque') td.a-span9, tr:contains('Maximum Torque') td.a-span9"attribute: "text"transform: "trim"target_field: "technicalDetails.torque"- name: "weight"selector_type: "css"selector: "tr:contains('Item Weight') td.a-span9"attribute: "text"transform: "trim"target_field: "technicalDetails.weight"- name: "dimensions"selector_type: "css"selector: "tr:contains('Product Dimensions') td.a-span9"attribute: "text"transform: "trim"target_field: "technicalDetails.dimensions"- name: "battery_included"selector_type: "css"selector: "tr:contains('Batteries Included') td.a-span9"attribute: "text"transforms:- "trim"- "to_boolean:Yes=true,No=false"target_field: "technicalDetails.batteryIncluded"- name: "cordless"selector_type: "css"selector: "tr:contains('Power Source') td.a-span9"attribute: "text"transforms:- "trim"- "to_boolean:Battery Powered=true,*=false"target_field: "technicalDetails.cordless"# Features- name: "features"selector_type: "css"selector: "#feature-bullets .a-list-item"attribute: "text"transform: "trim"target_field: "features"is_list: true# Reviews- name: "average_rating"selector_type: "css"selector: "#acrPopover .a-declarative"attribute: "title"transforms:- "regex_replace:(.*) out of 5 stars|$1"- "to_number"target_field: "reviews.averageRating"- name: "number_of_reviews"selector_type: "css"selector: "#acrCustomerReviewText"attribute: "text"transforms:- "regex_replace:([0-9,]+) ratings|$1"- "regex_replace:,||g"- "to_number"target_field: "reviews.numberOfReviews"# Availability- name: "in_stock"selector_type: "css"selector: "#availability"attribute: "text"transforms:- "trim"- "to_boolean:In Stock=true,*=false"target_field: "availability.inStock"- name: "delivery_options"selector_type: "css"selector: "#deliveryBlockMessage .a-list-item"attribute: "text"transform: "trim"target_field: "availability.deliveryOptions"is_list: true# Warranty- name: "warranty"selector_type: "css"selector: "tr:contains('Warranty Description') td.a-span9"attribute: "text"transform: "trim"target_field: "warranty"# Category info- name: "main_category"selector_type: "css"selector: "#wayfinding-breadcrumbs_feature_div li:last-child"attribute: "text"transform: "trim"target_field: "categoryInfo.mainCategory"- name: "sub_categories"selector_type: "css"selector: "#wayfinding-breadcrumbs_feature_div li:not(:last-child)"attribute: "text"transform: "trim"target_field: "categoryInfo.subCategories"is_list: true# Frequently bought together- name: "frequently_bought_together"selector_type: "css"selector: "#sims-consolidated-2_feature_div .a-carousel-card h2"attribute: "text"transform: "trim"target_field: "frequentlyBoughtTogether.name"is_list: true- name: "frequently_bought_together_links"selector_type: "css"selector: "#sims-consolidated-2_feature_div .a-carousel-card a"attribute: "href"transform: "trim"target_field: "frequentlyBoughtTogether.url"is_list: true
運行:
crwl https://a.co/d/17HZeGj -e dewalt-extraction-strategy.yaml -s dewalt-schema.json
因為:
可能是太頻繁,或我的 VPN 有在黑名單,沒抓到數據。
5. 指定一個JSON模式(JSON schema)文件的路徑 參數:-s, --schema [PATH]
crwl https://docs.crawl4ai.com/ -s [JSON schema 文件的路徑]
crwl https://docs.crawl4ai.com/ --schema [JSON schema 文件的路徑]
可以用 JSON schema (該模式) 文件來定義:從網站提取內容時的結構化的數據格式,如:
- 從網頁中提取的數據的結構、屬性和數據類型。它作為一個"模板",告訴爬蟲工具應該提取哪些信息以及如何組織這些信息。
- 當爬蟲處理網頁時,它會根據提供的JSON模式來識別和提取符合該模式定義的數據元素,然后將它們組織成符合模式結構的輸出。
?
例:從 Amazon.com 抓取 電動工具
從 Amazon.com 抓取 電動工具:DEWALT ATOMIC 20V MAX* 3/8 in. Cordless Impact Wrench with Hog Ring Anvil (Tool Only) (DCF923B)
鏈接(商品):?https://a.co/d/cfTKG4j??
內容包括:
- 基本產品信息:標題、品牌、型號和ASIN號
- 價格信息:當前價格、原價和折扣
- 產品圖片:所有產品圖片的URL數組
- 技術規格:電壓、扭矩、速度、重量、尺寸等
- 產品特點:產品特性和優勢的列表
- 分類信息:主類別和子類別
- 評論數據:平均評分、評論數量和評分分布
- 可用性信息:庫存狀態和配送選項
- 保修信息:產品保修詳情
- 相關產品:兼容配件和經常一起購買的產品
文件名:C:\temp\dewalt-schema.json
{"$schema": "http://json-schema.org/draft-07/schema#","title": "Amazon Power Tool Product Schema","description": "Schema for extracting DEWALT impact wrench product details from Amazon","type": "object","properties": {"productBasicInfo": {"type": "object","properties": {"title": {"type": "string","description": "Full product title"},"brand": {"type": "string","description": "Product brand name"},"model": {"type": "string","description": "Model number of the product"},"asin": {"type": "string","description": "Amazon Standard Identification Number"}},"required": ["title", "brand", "model"]},"pricing": {"type": "object","properties": {"currentPrice": {"type": "number","description": "Current listed price"},"originalPrice": {"type": "number","description": "Original price before any discounts"},"discount": {"type": "number","description": "Discount percentage if available"},"dealAvailable": {"type": "boolean","description": "Whether the product has an active deal"}},"required": ["currentPrice"]},"images": {"type": "array","items": {"type": "string","format": "uri","description": "URL of product image"},"description": "Collection of product image URLs"},"technicalDetails": {"type": "object","properties": {"voltage": {"type": "string","description": "Battery voltage"},"torque": {"type": "string","description": "Maximum torque rating"},"speed": {"type": "string","description": "Speed ratings (RPM)"},"weight": {"type": "string","description": "Weight of the tool"},"dimensions": {"type": "string","description": "Physical dimensions"},"batteryIncluded": {"type": "boolean","description": "Whether batteries are included"},"cordless": {"type": "boolean","description": "Whether the tool is cordless"}}},"features": {"type": "array","items": {"type": "string"},"description": "List of product features and benefits"},"categoryInfo": {"type": "object","properties": {"mainCategory": {"type": "string","description": "Main product category"},"subCategories": {"type": "array","items": {"type": "string"},"description": "Sub-categories the product belongs to"}}},"reviews": {"type": "object","properties": {"averageRating": {"type": "number","minimum": 0,"maximum": 5,"description": "Average customer rating out of 5"},"numberOfReviews": {"type": "integer","description": "Total number of customer reviews"},"ratingDistribution": {"type": "object","properties": {"5star": {"type": "integer"},"4star": {"type": "integer"},"3star": {"type": "integer"},"2star": {"type": "integer"},"1star": {"type": "integer"}},"description": "Distribution of ratings by star level"}}},"availability": {"type": "object","properties": {"inStock": {"type": "boolean","description": "Whether the product is in stock"},"deliveryOptions": {"type": "array","items": {"type": "string"},"description": "Available delivery options"},"estimatedDeliveryDate": {"type": "string","description": "Estimated delivery date range"}}},"warranty": {"type": "string","description": "Warranty information"},"compatibleAccessories": {"type": "array","items": {"type": "object","properties": {"name": {"type": "string"},"asin": {"type": "string"},"url": {"type": "string", "format": "uri"}}},"description": "Compatible accessories for this product"},"frequentlyBoughtTogether": {"type": "array","items": {"type": "object","properties": {"name": {"type": "string"},"asin": {"type": "string"},"url": {"type": "string", "format": "uri"}}},"description": "Products frequently bought together with this item"}},"required": ["productBasicInfo", "pricing", "images", "technicalDetails"]
}
運行:
crwl https://a.co/d/17HZeGj -s dewalt-schema.json
6. 指定瀏覽器配置文件(JSON/YAML),參數:-B,--browser-config [PATH]
crwl https://docs.crawl4ai.com/ -B [JSON 或 YAML 格式 配置文件的路徑]
crwl https://docs.crawl4ai.com/ -browser-config [JSON 或 YAML 格式 配置文件的路徑]
指定瀏覽器配置文件的路徑,該文件以YAML或JSON格式定義爬蟲使用的瀏覽器行為和設置。許多網站使用 JavaScript 動態加載內容或實現反爬機制。瀏覽器配置文件讓你能控制爬蟲如何與網頁交互,特別重要。
1)瀏覽器配置文件的主要功能
- 瀏覽器類型設置
- 指定使用瀏覽器引擎(如Chromium、Firefox)
- 設置瀏覽器的版本
- 請求頭和身份識別
- 自定義User-Agent
- 設置HTTP頭部信息
- 配置Cookie處理方式
- 渲染控制
- 等待頁面完全加載的時間
- 設置JavaScript執行超時
- 控制是否加載圖片和其他媒體資源
- 代理和網絡設置
- 配置代理服務器
- 設置網絡請求超時
- 控制并發連接數
- 交互行為
- 自動滾動頁面
- 模擬鼠標移動
- 配置點擊行為
2)例:配置文件
browser:# 基本瀏覽器設置type: "chromium" # 使用Chromium瀏覽器headless: true # 無頭模式(不顯示瀏覽器界面)# 超時和等待設置page_load_timeout: 30000 # 頁面加載超時(毫秒)default_wait_time: 5000 # 默認等待時間(毫秒)# 請求頭設置user_agent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"# 媒體和資源設置block_images: true # 阻止加載圖像block_css: false # 不阻止CSSblock_fonts: true # 阻止字體加載# 代理設置proxy:server: "http://proxy-server.example.com:8080"username: "proxy_user"password: "proxy_password"# Cookie和存儲設置cookies_enabled: truelocal_storage_enabled: true# 瀏覽器窗口設置viewport:width: 1920height: 1080# 交互行為設置auto_scroll:enabled: truedelay: 500 # 滾動間隔(毫秒)scroll_amount: 200 # 每次滾動像素max_scrolls: 20 # 最大滾動次數
上面有解釋,打字太累,不再重復。
3)使用場景
- 有的網站使用“無限滾動”或"加載更多"按鈕,需要配置自動滾動和點擊行為
- 繞過反爬策略,調整User-Agent和請求頻率,使爬蟲行為更像真人
- 通過阻止加載不需要的資源 (像:圖片、字體、廣告)提高爬取效率
- 使用代理網絡訪問,可以 DELETED 區域限制的內容
- 按照網站特點調整超時、等待時間等
- 常與 -e -c -b 共同工作
7. 指定內容過濾配置文件,參數:-f, --filter-config PATH
crwl https://docs.crawl4ai.com/ -f [如:YAML 格式 配置文件的路徑]
crwl https://docs.crawl4ai.com/ --filter-config [如:YAML 格式 配置文件的路徑]
文件定義了如何篩選和處理爬取到的數據,屏蔽大量無關內容的網頁。
1)內容過濾配置文件的主要功能
- 含與排除規則
- 基于關鍵詞或正則表達式包含特定內容
- 排除不相關的內容塊或元素
- 設置優先級規則處理內容沖突
- 數據清理
- 去除HTML標簽、廣告內容
- 清理多余空白、特殊字符
- 標準化日期、價格等格式
- 內容過濾
- 基于文本長度篩選內容
- 過濾低質量或重復內容
- 評估內容的相關性得分
- 內容分類與標記
- 將提取的內容按類型分類
- 為不同內容塊添加標簽
- 確定內容的層次結構
2)例:過濾配置文件
filters:# 文本清理過濾器- name: "text_cleanup"type: "text_transform"enabled: trueactions:- replace: ["[\r\n\t]+", " "] # 替換多行為單個空格- replace: ["\s{2,}", " "] # 替換多個空格為單個空格- replace: [" ", " "] # 替換HTML特殊字符- trim: true # 去除首尾空白# 內容包含過濾器- name: "content_inclusion"type: "inclusion"enabled: truerules:- field: "description"patterns: - "DEWALT"- "Impact Wrench"- "cordless"match_type: "any" # 匹配任一關鍵詞即包含# 內容排除過濾器- name: "content_exclusion"type: "exclusion"enabled: truerules:- field: "description"patterns:- "unavailable"- "out of stock"- "advertisement"match_type: "any" # 匹配任一關鍵詞即排除# 長度過濾器- name: "length_filter"type: "length"enabled: truerules:- field: "review"min_length: 50 # 最小長度(字符)max_length: 5000 # 最大長度(字符)# 內容分類過濾器- name: "content_classifier"type: "classifier"enabled: truerules:- field: "text"classifications:- name: "product_spec"patterns: ["specification", "technical detail", "dimension"]- name: "user_review"patterns: ["review", "rating", "stars", "purchased"]- name: "shipping_info"patterns: ["shipping", "delivery", "arrive"]target_field: "content_type" # 將分類結果存儲到此字段
3)使用場景
- 過濾產品描述、規格和價格,排除廣告和推薦商品
- 提取有效評論,過濾掉垃圾評論和自動生成內容
- 篩選特定主題的新聞,排除不相關的廣告和導航元素
- 從長篇內容中只提取所需的章節或段落
- 保留特定語言的內容,過濾其他語言
8.?使用大型語言模型(LLM)從網頁中提取結構化數據,參數:-j,--json-extract TEXT
crwl https://docs.crawl4ai.com/ -j [給LLM 的提示詞 PROMPT]
crwl https://docs.crawl4ai.com/ --json-extract [給LLM 的提示詞 PROMPT]
指定想要從爬取的網頁中提取什么類型的結構化數據,而且可以通過提供描述來引導 LLM 如何進行提取。支持的模型很多,見官網:Providers | liteLLM (https://docs.litellm.ai/docs/providers)?
需要有 API KEY OF LLM
例:從網站提取信息
crwl https://docs.crawl4ai.com/ -j “如何配置 LLM-based extraction”
9.?把結果保存到文件里,參數:?-O, --output-file PATH?
crwl https://docs.crawl4ai.com/ -O [輸出結果的路徑與文件名]
crwl https://docs.crawl4ai.com/ --output-file [輸出結果的路徑與文件名]
- 將結果保存到文件中,方便后續使用
- 方便將數據傳遞給其他程序或工具進行后續處理
- ?結合之前的 -o, --output 選項,保存為不同格式(json、markdown 等),見 CLI 第1個介紹
10.?對已爬取的網頁內容提出自然語言問題,參數,-q, --question?[給LLM 的提示詞 PROMPT ]
crwl https://docs.crawl4ai.com/ -q [給LLM 的提示詞 PROMPT]
crwl https://docs.crawl4ai.com/ --question [給LLM 的提示詞 PROMPT]
依賴于大型語言模型(LLM),首先 crwl 爬取并處理指定網站的內容,工具會分析爬取的內容,找到相關信息并提供答案。
例:
crwl https://docs.crawl4ai.com/ -q "如何配置 LLM-based extraction"
11. 指定特定的瀏覽器配置文件來運行,參數:-p, --profile TEXT
crwl https://docs.crawl4ai.com/ -p TEXT
crwl https://docs.crawl4ai.com/ --profile TEXT
需要提前配置 Profiles 配置文件,命令:
crwl profiles
LLM 配置方法
1.?初始設置
首次設置時,會提示輸入 LLM 提供商和 API 令牌,然后將配置保存在 ~/.crawl4ai/global.yml 文件中。文件內容:
2.?使用?-e
選項,指定LLM配置文件
文件:extract_llm.yml
type: "llm"
provider: "openai/gpt-4"
instruction: "提取所有文章的標題和鏈接"
api_token: "token / key"
params:temperature: 0.3max_tokens: 1000
運行:
crwl https://docs.crawl4ai.com/ -e extract_llm.yml
小結:
碼字太多,也未必有人看,作為自用文就寫到這里。
CRAWL4AI 是一個強大的爬蟲(刮刀)軟件,特別是支持 LLM 的使用。 以上只是 CLI 的功能介紹,還涉及到配置文件的示例。
在這篇文章只是詳細的介紹 CLI 命令行的使用,也有詳細的示例來介紹這些配置文件。但這些也只是 APP 的小部分,更多還是要去參考官方 Doc.? 見文章開頭的鏈接。