程技 爬虫 Crawlee JavaScript 使用教程 Rich 2026-12-03 2026-12-03 Crawlee JavaScript 使用教程
适用版本:Crawlee 3.18(2026-12 官方文档) 运行环境:Node.js 16+(建议 Node.js 18/20 LTS) 说明:本文示例使用 ESM。在 package.json 中加入 "type": "module",或使用 .mjs 后缀。
1. Crawlee 是什么 Crawlee 是 Apify 团队维护的 Node.js 爬虫框架,核心特点是:
统一接口 :HTTP 爬虫与浏览器爬虫共用一套 API,切换成本低。
自动队列 :内置持久化请求队列,支持递归抓取、广度/深度优先。
自动扩缩容 :根据 CPU / 内存自动调整并发。
拟人化 :浏览器指纹、请求头、代理轮换、Session 管理开箱即用。
结构化存储 :Dataset 存表格数据,KeyValueStore 存文件/状态。
工程化能力 :日志、重试、失败请求处理、生命周期钩子、Docker 部署模板。
典型场景:新闻聚合、电商价格监控、招聘信息采集、公开数据监控(如金属价格行情表)。
2. 安装与项目初始化 2.1 方式一:CLI 快速创建(推荐新手) 1 2 3 npx crawlee create my-crawler cd my-crawlernpm start
CLI 会安装依赖并生成可运行示例,包含 package.json、入口文件和 storage/ 目录结构。
2.2 方式二:手动安装 1 2 3 mkdir my-crawler && cd my-crawlernpm init -y npm install crawlee
如果使用 Playwright 爬虫:
1 2 npm install crawlee playwright npx playwright install chromium
如果使用 Puppeteer 爬虫:
1 npm install crawlee puppeteer
设置 ESM,编辑 package.json:
1 2 3 4 5 6 7 8 9 { "type" : "module" , "scripts" : { "start" : "node src/main.js" } , "dependencies" : { "crawlee" : "^3.18.0" } }
3. 三种爬虫怎么选
爬虫类
底层
能否执行 JS
适用场景
速度
CheerioCrawler
got-scraping + Cheerio
否
静态 HTML、JSON API、列表页
最快
PlaywrightCrawler
Playwright
是
动态渲染、登录、点击、截图;支持 Chromium/Firefox/WebKit
较慢
PuppeteerCrawler
Puppeteer
是
已熟悉 Puppeteer、只需 Chromium
较慢
经验法则 :优先 CheerioCrawler;只有页面数据由 JavaScript 渲染或需要交互时,再升级到 PlaywrightCrawler。
4. 第一个爬虫:抓取页面标题并递归跟进链接 新建 src/main.js:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 import { CheerioCrawler , Dataset } from 'crawlee' ;const crawler = new CheerioCrawler ({ async requestHandler ({ request, $, enqueueLinks, log } ) { const title = $('title' ).text ().trim (); log.info (`标题:${title} | ${request.loadedUrl} ` ); await Dataset .pushData ({ url : request.loadedUrl , title, }); await enqueueLinks (); }, maxRequestsPerCrawl : 20 , }); await crawler.run (['https://crawlee.dev' ]);
运行:
输出示例:
1 2 INFO CheerioCrawler: Title of https://crawlee.dev/ is 'Crawlee · Build reliable crawlers. Fast.' INFO CheerioCrawler: Title of https://crawlee.dev/js/docs/quick-start is 'Quick Start | Crawlee'
结果文件:
1 2 3 4 storage/ datasets/default/000000001.json request_queues/default/entries.json key_value_stores/default/
代码要点
requestHandler 是处理入口,上下文包含 request、$(Cheerio 对象)、enqueueLinks、log、session 等。
Dataset.pushData() 写一行结构化数据;enqueueLinks() 把页面链接加入队列。
crawler.run([...]) 启动爬虫并等待结束。
maxRequestsPerCrawl 强烈建议始终设置,防止配置错误导致无限运行。
5. 核心概念与存储 5.1 请求队列 RequestQueue 适合“从若干入口出发,边抓边发现新链接”的场景。队列默认持久化到磁盘,可断点续跑。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 import { CheerioCrawler } from 'crawlee' ;const crawler = new CheerioCrawler ({ async requestHandler ({ request, crawler, enqueueLinks } ) { await crawler.addRequests ([ { url : 'https://example.com/extra' , label : 'DETAIL' }, ]); await enqueueLinks ({ selector : 'a.product-link' , label : 'DETAIL' , userData : { source : request.loadedUrl }, }); }, }); await crawler.run (['https://example.com/category' ]);
5.2 请求列表 RequestList 适合“URL 全部已知、运行中不会再增加”的批量任务(百万级 URL 也适用),初始化后不可变。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 import { RequestList , CheerioCrawler } from 'crawlee' ;const sources = [ { url : 'https://example.com/p/1' }, { url : 'https://example.com/p/2' }, ]; const requestList = await RequestList .open ('my-list' , sources);const crawler = new CheerioCrawler ({ requestList, async requestHandler ({ $, request } ) { console .log (request.url , $('title' ).text ()); }, }); await crawler.run ();
现代 Crawlee 中 addRequests() 已支持批量添加,大多数场景只用 RequestQueue 即可 ,不必组合 RequestList。
5.3 Dataset:结构化结果 1 2 3 4 5 6 7 8 9 10 11 import { Dataset } from 'crawlee' ;await Dataset .pushData ({ name : '沪金' , price : 780.2 });const dataset = await Dataset .open ('metal-prices' );await dataset.pushData ([ { name : '沪银' , price : 9200 }, { name : '沪铜' , price : 74500 }, ]);
特点:只追加、不可修改删除;每条记录是一个 JSON 文件,适合后续导入数据库或 Excel。
5.4 KeyValueStore:文件与状态 1 2 3 4 5 6 7 8 9 import { KeyValueStore } from 'crawlee' ;const store = await KeyValueStore .open ('my-store' );await store.setValue ('checkpoint' , { lastPage : 12 });const checkpoint = await store.getValue ('checkpoint' );await KeyValueStore .setValue ('OUTPUT' , { done : true });
适合保存截图、PDF、爬虫检查点等。
5.5 存储目录与环境 默认存储目录为当前工作目录下的 ./storage。可用环境变量覆盖:
1 CRAWLEE_STORAGE_DIR=/data/crawler-storage node src/main.js
常用环境变量:
变量
作用
CRAWLEE_STORAGE_DIR
修改存储根目录
CRAWLEE_PURGE_ON_START=false
启动时不清空默认存储(追加数据)
CRAWLEE_HEADLESS=1
无头模式运行浏览器
CRAWLEE_LOG_LEVEL=DEBUG
调整日志级别
注意:默认情况下,Crawlee 在每次运行前会清理默认存储。若希望结果累积,请设置 CRAWLEE_PURGE_ON_START=false。
6. 多页面路由:用 label 分流处理逻辑 网站通常有“列表页 + 详情页”两类页面。用 label 标记请求,再在 router 中注册不同处理器。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 import { CheerioCrawler , Dataset } from 'crawlee' ;const crawler = new CheerioCrawler ();crawler.router .addDefaultHandler (async ({ $, enqueueLinks, log }) => { log.info ('处理列表页' ); await enqueueLinks ({ selector : 'a.detail' , label : 'DETAIL' , }); }); crawler.router .addHandler ('DETAIL' , async ({ $, request }) => { const name = $('.name' ).text ().trim (); const price = $('.price' ).text ().trim (); await Dataset .pushData ({ url : request.loadedUrl , name, price, }); }); await crawler.run (['https://example.com/list' ]);
也可以用工厂函数一次性定义:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 import { CheerioCrawler , createCheerioRouter, Dataset } from 'crawlee' ;const router = createCheerioRouter ({ DETAIL : async ({ $, request }) => { await Dataset .pushData ({ url : request.loadedUrl , title : $('h1' ).text () }); }, }); router.addDefaultHandler (async ({ enqueueLinks }) => { await enqueueLinks ({ selector : 'a.detail' , label : 'DETAIL' }); }); const crawler = new CheerioCrawler ({ requestHandler : router });await crawler.run (['https://example.com/list' ]);
6.1 TypeScript 类型安全路由(v3.18 新特性) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 import { createCheerioRouter } from 'crawlee' ;import type { CheerioCrawlingContext } from 'crawlee' ;interface Routes { DETAIL : { sku : string }; LIST : { page : number }; } const router = createCheerioRouter<CheerioCrawlingContext , Routes >();router.addHandler ('DETAIL' , async ({ request }) => { console .log (request.userData .sku ); });
若使用 JavaScript,可忽略类型参数,仅用 label 字符串分流。
7. 动态渲染页面:PlaywrightCrawler 当页面数据由 JavaScript 渲染,或需要点击/登录/截图时:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 import { PlaywrightCrawler , Dataset } from 'crawlee' ;const crawler = new PlaywrightCrawler ({ async requestHandler ({ page, request, enqueueLinks, log } ) { await page.waitForLoadState ('networkidle' ); const title = await page.title (); const rows = await page.locator ('table tbody tr' ).allTextContents (); log.info (`${title} :${rows.length} 行` ); for (const row of rows) { await Dataset .pushData ({ url : request.loadedUrl , text : row.trim (), }); } await enqueueLinks (); }, headless : true , maxRequestsPerCrawl : 20 , }); await crawler.run (['https://crawlee.dev' ]);
与 Cheerio 的差异
用 page 对象操作浏览器:page.locator()、page.click()、page.screenshot()。
requestHandler 内的 $ 不再可用,改用 Playwright API。
首次运行需要 npx playwright install chromium 下载浏览器。
8. 配置、稳定性与错误处理 8.1 常用爬虫选项 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 import { CheerioCrawler , log, LogLevel } from 'crawlee' ;log.setLevel (LogLevel .DEBUG ); const crawler = new CheerioCrawler ({ minConcurrency : 5 , maxConcurrency : 30 , maxRequestRetries : 2 , requestHandlerTimeoutSecs : 30 , maxRequestsPerCrawl : 100 , maxSessionRotations : 10 , async requestHandler ({ request, $, log } ) { log.debug (`处理 ${request.url} ` ); }, failedRequestHandler ({ request, error } ) { log.error (`最终失败:${request.url} - ${error?.message} ` ); }, }); await crawler.run (['https://example.com' ]);
8.2 三种配置方式(优先级由低到高)
项目根目录 crawlee.json
1 2 3 4 { "persistStateIntervalMillis" : 10000 , "logLevel" : "DEBUG" }
代码中的 Configuration
1 2 3 4 5 6 7 8 import { CheerioCrawler , Configuration } from 'crawlee' ;const config = new Configuration ({ persistStateIntervalMillis : 10_000 });const crawler = new CheerioCrawler ({}, config);const globalConfig = Configuration .getGlobalConfig ();globalConfig.set ('persistStateIntervalMillis' , 10_000 );
环境变量(覆盖前两者),如 CRAWLEE_LOG_LEVEL=DEBUG。
8.3 生命周期钩子(浏览器爬虫) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 const crawler = new PlaywrightCrawler ({ preNavigationHooks : [ async ({ request }, gotoOptions) => { gotoOptions.waitUntil = 'domcontentloaded' ; }, ], postNavigationHooks : [ async ({ page }) => { await page.waitForTimeout (500 ); }, ], });
9. 代理、Session 与浏览器指纹 9.1 静态代理列表轮换 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 import { CheerioCrawler , ProxyConfiguration } from 'crawlee' ;const proxyConfiguration = new ProxyConfiguration ({ proxyUrls : [ 'http://user:[email protected] :8000' , 'http://user:[email protected] :8000' , null , ], }); const crawler = new CheerioCrawler ({ proxyConfiguration, async requestHandler ({ proxyInfo } ) { console .log ('当前代理:' , proxyInfo?.url ); }, });
9.2 分级代理(被封自动升级) 1 2 3 4 5 6 7 8 const proxyConfiguration = new ProxyConfiguration ({ tieredProxyUrls : [ [null ], ['http://cheap-proxy.example.com' ], ['http://better-1.example.com' , 'http://better-2.example.com' ], ['http://premium.example.com' ], ], });
Crawlee 检测到被封后会自动切到更高层级,并定期回探低层级代理。
9.3 Session:绑定 IP、Cookie 与状态 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 const crawler = new CheerioCrawler ({ useSessionPool : true , persistCookiesPerSession : true , sessionPoolOptions : { maxPoolSize : 100 }, proxyConfiguration, async requestHandler ({ $, session } ) { const title = $('title' ).text (); if (title.includes ('Blocked' )) { session?.retire (); } else if (title.includes ('Verify' )) { session?.markBad (); } }, });
9.4 浏览器指纹 PlaywrightCrawler / PuppeteerCrawler 默认开启拟人化指纹,一般无需配置:
1 2 3 4 5 6 7 8 9 10 11 const crawler = new PlaywrightCrawler ({ browserPoolOptions : { useFingerprints : true , fingerprintOptions : { fingerprintGeneratorOptions : { devices : ['desktop' ], operatingSystems : ['windows' ], }, }, }, });
合规提醒:抓取前请阅读目标站点 robots.txt 与服务条款,控制频率,只采集公开数据,不要绕过登录墙或安全机制。
10. 实战模板:金属价格表采集器 假设有一个公开行情列表页,包含表格行:品种 | 最新价 | 涨跌 | 单位,并有“下一页”链接。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 import { CheerioCrawler , Dataset , log, LogLevel } from 'crawlee' ;log.setLevel (LogLevel .INFO ); const crawler = new CheerioCrawler ({ minConcurrency : 2 , maxConcurrency : 8 , maxRequestsPerCrawl : 30 , maxRequestRetries : 2 , async requestHandler ({ request, $, enqueueLinks } ) { const scrapedAt = new Date ().toISOString (); const rows = []; $('table.price-table tbody tr' ).each ((_, tr ) => { const tds = $(tr).find ('td' ); const name = $(tds[0 ]).text ().trim (); const priceText = $(tds[1 ]).text ().trim (); const changeText = $(tds[2 ]).text ().trim (); const unit = $(tds[3 ]).text ().trim () || '元/吨' ; if (!name || !priceText) return ; const price = Number (priceText.replace (/,/g , '' )); const change = Number (changeText.replace (/[+%]/g , '' )); rows.push ({ name, price : Number .isFinite (price) ? price : null , change : Number .isFinite (change) ? change : null , unit, sourceUrl : request.loadedUrl , scrapedAt, }); }); if (rows.length ) { await Dataset .pushData (rows); log.info (`已保存 ${rows.length} 条行情:${request.loadedUrl} ` ); } else { log.warning (`未解析到行情数据,请检查选择器:${request.loadedUrl} ` ); } await enqueueLinks ({ selector : 'a.next-page' , label : 'LIST' , }); }, failedRequestHandler ({ request, error } ) { log.error (`采集失败 ${request.url} : ${error?.message} ` ); }, }); await crawler.run (['https://example.com/metal-prices' ]);
后续处理建议
将 storage/datasets/default/*.json 导入 MySQL / SQLite,按 scrapedAt 建时间序列。
在入库前按 name + scrapedAt 去重,避免重试导致重复记录。
若页面价格在浏览器中渲染,把 CheerioCrawler 换成 PlaywrightCrawler,表格解析改为 page.locator()。
11. 调试与常见问题
问题
排查方向
没有抓取到数据
用 log.setLevel(LogLevel.DEBUG);确认选择器;检查页面是否 JS 渲染
抓取结果为空但无报错
目标站点返回反爬页;打印 $.html().slice(0, 500) 检查
被 403 / 429
降低 maxConcurrency;加代理;启用 Session;设置 maxRequestRetries
Playwright 启动失败
执行 npx playwright install chromium;确认系统依赖
存储结果被清空
默认启动会 purge;设置 CRAWLEE_PURGE_ON_START=false
爬虫跑不完
检查 enqueueLinks() 是否抓到无关链接;用 maxRequestsPerCrawl 限制;加 selector/include 过滤
ESM 报错 Cannot use import statement
在 package.json 加 "type": "module" 或改用 .mjs
enqueueLinks() 过滤示例:
1 2 3 4 await enqueueLinks ({ globs : ['https://example.com/metal-prices/**' ], exclude : ['**/login**' , '**/cart**' ], });
12. 速查表 1 2 3 4 5 6 7 8 9 10 11 12 13 import { CheerioCrawler , PlaywrightCrawler , PuppeteerCrawler , Dataset , KeyValueStore , RequestQueue , RequestList , ProxyConfiguration , Configuration , log, LogLevel , } from 'crawlee' ;
需求
API
抓静态页
new CheerioCrawler({ requestHandler })
抓动态页
new PlaywrightCrawler({ requestHandler })
启动并传入种子 URL
await crawler.run([url])
追加 URL
await crawler.addRequests([...])
自动发现链接
await enqueueLinks({ selector, label })
保存一行数据
await Dataset.pushData(obj)
保存文件/状态
await KeyValueStore.setValue(key, value)
按 label 分流
crawler.router.addHandler('LABEL', fn)
限制总量
maxRequestsPerCrawl: 100
失败处理
failedRequestHandler({ request, error })
代理轮换
new ProxyConfiguration({ proxyUrls })
会话管理
useSessionPool: true
13. 参考链接