API 全解析:HttpCrawler、FileDownload 與流式下載工具)
Crawlee 的 HTTP 爬蟲crawlee/httpAPI 全解析HttpCrawler、FileDownload 與流式下載工具【免費下載鏈接】crawleeCrawlee—A web scraping and browser automation library for Node.js to build reliable crawlers. In JavaScript and TypeScript. Extract data for AI, LLMs, RAG, or GPTs. Download HTML, PDF, JPG, PNG, and other files from websites. Works with Puppeteer, Playwright, Cheerio, JSDOM, and raw HTTP. Both headful and headless mode. With proxy rotation.項目地址: https://gitcode.com/GitHub_Trending/cr/crawlee本文以crawlee/http包的公開 API 報告crawlee-http.api.md為主線系統拆解 Crawlee 中純 HTTP 爬蟲族的完整能力HttpCrawler的選項、上下文與導航管線FileDownload文件下載爬蟲以及MinimumSpeedStream/ByteCounterStream兩個流式下載輔助工具。讀完本文你將能夠不依賴瀏覽器、僅用原生 HTTP 請求高并發抓取 HTML / JSON / 任意 MIME 內容并寫出帶下載進度與最低網速保護的可靠文件下載器。包定位crawlee/http在整個倉庫中的位置在 Crawlee 的 monorepo 中crawlee/http對應倉庫根目錄下的 packages/http-crawler其入口文件 packages/http-crawler/src/index.ts 做了三件事export * from crawlee/basic; export * from ./internals/http-crawler.js; export * from ./internals/file-download.js;也就是說該包除了自身新增的HttpCrawler、FileDownload及相關類型與工具函數外還完整再導出crawlee/basic即BasicCrawler、ConcurrencySystem、ContextPipeline、Router等基礎能力因此從crawlee/http一個入口即可拿到構建爬蟲所需的全部基礎設施。按 API Extractor 報告的導出清單本包對外暴露的public符號包括類別導出符號爬蟲類HttpCrawler、FileDownload上下文HttpCrawlingContext、InternalHttpCrawlingContext、FileDownloadCrawlingContext、CrawlingContextWithResponse選項HttpCrawlerOptions處理器類型HttpRequestHandler、HttpErrorHandler、HttpHook、FileDownloadRequestHandler、FileDownloadErrorHandler、FileDownloadHook路由工廠createHttpRouter、createFileRouter流工具MinimumSpeedStream、ByteCounterStream常量HTTP_OPTIMIZED_CONCURRENCY_SYSTEM_OPTIONS注CrawlingContextWithResponse在 API 報告中標注為 Not exported by the entry point; reachable only as a referenced type即它僅作為內部引用類型存在用戶代碼中無需直接 import。HttpCrawler純 HTTP 請求的并行爬蟲設計定位HttpCrawler的類注釋http-crawler.ts明確了它的定位通過普通 HTTP 請求下載 URL不執行任何 HTML 解析與客戶端 JavaScript支持從靜態 URL 列表RequestList或動態請求隊列RequestQueue中取 URL實現遞歸爬取在數據帶寬利用上非常快速高效但如果目標站點依賴 JavaScript 渲染內容則應改用PuppeteerCrawler或PlaywrightCrawler請求源統一由requestManager提供RequestQueue本身就是一個 request manager如需只讀源如RequestList與隊列組合可通過requestLoader.toTandem()得到RequestManagerTandem再傳入舊式的requestList/requestQueue選項仍被接受但已標記為 deprecated會在內部折疊進同一個requestManager。最小可用示例倉庫文檔示例 docs/examples/http_crawler.ts 展示了完整用法其中核心片段如下import { HttpCrawler, log, LogLevel } from crawlee; log.setLevel(LogLevel.DEBUG); const crawler new HttpCrawler({ minConcurrency: 10, maxConcurrency: 50, maxRequestRetries: 1, requestHandlerTimeoutSecs: 30, maxRequestsPerCrawl: 10, async requestHandler({ pushData, request, body }) { log.debug(Processing ${request.url}...); await pushData({ url: request.url, body, }); }, failedRequestHandler({ request }) { log.debug(Request ${request.url} failed twice.); }, }); await crawler.run([https://crawlee.dev]);類聲明中的構造函數簽名要求傳入HttpCrawlerOptions RequireContextPipelineInternalHttpCrawlingContext, Contexthttp-crawler.ts并且所有選項都會經過 zod 模式校驗parseArgumentHttpCrawler.optionsSchema見 http-crawler.ts非法參數會在構造階段直接報錯。爬取上下文body、json、contentType 與 Cheerio 解析HttpCrawlingContext泛型UserData與JSONData繼承自InternalHttpCrawlingContext后者在 http-crawler.ts 中定義了以下成員成員類型說明requestLoadedRequest已成功加載并導航到的請求對象含loadedUrlresponseResponseHTTP 響應對象狀態碼、頭信息等bodystring \| Buffer響應體text/html、application/xhtmlxml、application/xml返回字符串其余 MIME 類型返回BufferjsonJSONData當響應 Content-Type 為application/json時為解析后的 JSON 對象否則為nullcontentType{ type: string; encoding: BufferEncoding }解析后的 Content-TypewaitForSelector(selector, timeoutMs?)Promisevoid等待選擇器匹配的元素出現未匹配則拋錯文檔注明 timeout 參數實際被忽略parseWithCheerio(selector?, timeoutMs?)PromiseCheerioAPI用 Cheerio 加載 body傳入selector時先等待其出現否則拋錯json的懶加載實現值得注意http-crawler.ts它是一個 getter僅當contentType.type application/json時才執行JSON.parse否則返回null——因此非 JSON 響應不會產生無謂的解析開銷。waitForSelector與parseWithCheerio在 processHttpResponse 中基于cheerio.load()實現。測試用例 test/core/crawlers/http_crawler.test.ts 驗證了parseWithCheerio(title)能正確取出頁面標題。HttpCrawlerOptions 全參數詳解所有HttpCrawlerOptions參數都繼承自BasicCrawlerOptionsHTTP 專屬選項如下默認值取自 optionsShape選項類型默認值說明navigationTimeoutSecsnumber30整個導航階段的超時秒。這是一個被preNavigationHooks、HTTP 請求、postNavigationHooks共享的單一預算窗口慢的 hook 會占用請求本身的時長與只計時 request handler 的requestHandlerTimeoutSecs相互獨立ignoreTlsErrorsbooleantrue是否忽略 TLS/SSL 證書錯誤會以ignoreTlsErrors轉發給底層 HTTP 客戶端。內置的 impit 與 got-scraping 客戶端支持原生 fetch 回退無法禁用 TLS 校驗只會給出警告preNavigationHooksInternalHttpHook[][]導航前按序執行的異步鉤子可設置額外 cookie 等。可返回部分對象并入上下文postNavigationHooks數組[]導航后按序執行的異步鉤子可檢查導航結果、覆蓋response如挑戰頁后重取additionalMimeTypesstring[][]額外允許加載處理的 MIME 類型。默認只支持text/html、application/xhtmlxml、text/xml、application/xml、application/jsonsuggestResponseEncodingstring無當響應頭未提供有效編碼時回退到指定編碼如windows-1250forceResponseEncodingstring無強制使用指定編碼忽略響應頭聲明saveResponseCookiesbooleantrue自動把響應的Set-Cookie保存/更新到 Session后續請求自動攜帶幾個關鍵行為細節編碼優先級forceResponseEncoding優先于suggestResponseEncoding當兩者同時設置時構造器會打印 warning Using forceResponseEncodinghttp-crawler.ts。additionalMimeTypes 支持通配傳入*/*表示接受任意類型其余值會經過content-type庫解析解析失敗會在構造時拋錯extendSupportedMimeTypes。測試用例 http_crawler.test.ts 使用*/*驗證了通配行為。不支持的類型直接跳過導航完成后若響應 Content-Type 不在支持集合內且不是瞬時錯誤status 500或命中blockedStatusCodes會設置request.noRetry true并拋錯跳過該資源abortDownloadOfBody。導航管線一次請求的完整生命周期buildContextPipeline()http-crawler.ts揭示了 HTTP 爬蟲內部的處理順序prepareHttpRequest → preNavigationHooks每個都在共享導航窗口內計時 → makeHttpRequest真正的 HTTP 請求受剩余窗口約束 → postNavigationHooks含內置的 abortDownloadOfBody → processHttpResponse解析 body、編碼、cookie、構造上下文成員 → handleBlockedRequestByContent反爬識別 → requestHandler用戶代碼要點單一導航窗口preNavigationHooks 請求 postNavigationHooks共享navigationTimeoutSecs的預算。每個步驟通過remainingNavigationWindowMillis計算剩余時間用addTimeoutToPromise包一層超時拋出TimeoutError文案為 Navigation timed out after N seconds.。即使服務端緩慢地流式傳輸 bodybody 讀取也受同一窗口約束processHttpResponse。skipNavigation 支持若request.skipNavigation為真prepareHttpRequest會安裝拋出NavigationSkippedError的 getterloadedUrl、response、contentType、body、json、waitForSelector、parseWithCheerio跳過導航階段但保留上下文管線其余部分。429 限流響應狀態為 429 時會解析retry-after頭并調用recordDomainRateLimit命中則拋出RequestThrottledError并主動取消 body 以釋放連接processHttpResponse。阻塞識別isRequestBlockedhttp-crawler.ts對 HTML/XML 內容用parseWithCheerio檢查RETRY_CSS_SELECTORS來自crawlee/utils/internal或檢查狀態碼是否命中blockedStatusCodes命中即拋SessionError觸發會話輪換重試。Cookie 回寫saveResponseCookies開啟時getCookiesFromResponse提取的 cookie 會寫入session.cookieJarprocessHttpResponse關閉時則傳入 session cookie jar 的克隆使寫入被丟棄requestAsBrowser。響應編碼與字符集處理parseResponsehttp-crawler.ts與 utils.ts 共同負責編碼處理先調用parseContentTypeFromResponse解析 Content-Type 頭若頭部缺失或無法解析則回退到文件擴展名推斷 MIMEmime.contentType(extname(url.pathname))最終兜底為application/octet-stream; charsetutf-8對 HTML/XML若頭部無 charset 且未強制編碼會掃描 body 前 1024 字節latin1 方式匹配meta charset...或http-equivContent-Type中的聲明extractCharsetFromHtmlBytes這是 HTML 規范字節流預掃描算法的簡化實現編碼優先級forceResponseEncoding 響應頭/HTML 聲明 suggestResponseEncodingutf-8非 Node 內置編碼如 windows-1250通過iconv-lite以流式方式重編碼為 UTF-8encodeResponse不支持的編碼會直接拋錯4xx/5xx 錯誤響應會嘗試按 JSON 解析出message字段否則取 body 前 100 個字符構造錯誤信息。HTTP 優化的默認并發系統由于純 HTTP 爬取幾乎不占用事件循環HttpCrawler提供了專門調優過的默認并發參數。常量HTTP_OPTIMIZED_CONCURRENCY_SYSTEM_OPTIONShttp-crawler.ts定義為export const HTTP_OPTIMIZED_CONCURRENCY_SYSTEM_OPTIONS: ConcurrencySystemOptions { desiredConcurrency: 10, loadSignals: { eventLoop: { snapshotIntervalSecs: 2, maxBlockedMillis: 100, overloadedRatio: 0.7, }, }, };HttpCrawler.createDefaultConcurrencySystemhttp-crawler.ts會把這些選項與用戶傳入的minConcurrency/maxConcurrency/maxRequestsPerMinute合并——用戶快捷選項在上層覆蓋。對應測試 http_crawler.test.ts 驗證了三點默認系統的起始desiredConcurrency為 10用戶設置maxConcurrency: 5時起始并發被上限壓到 5但 HTTP 優化參數并未被丟棄initialConcurrency: 3可以覆蓋 HTTP 優化的起始并發。注意如果你自行傳入concurrencySystem它會整體替換默認系統包括上述調優。想保留調優需要手動展開常量例如new ConcurrencySystem({ ...HTTP_OPTIMIZED_CONCURRENCY_SYSTEM_OPTIONS, maxConcurrency: 50 })。createHttpRouter基于標簽的路由createHttpRouterhttp-crawler.ts是Router.createHttpCrawlingContext()的快捷方式返回的RouterHandler可直接作為requestHandlerimport { HttpCrawler, createHttpRouter } from crawlee; const router createHttpRouter(); router.addHandler(label-a, async (ctx) { ctx.log.info(處理 label-a); }); router.addDefaultHandler(async (ctx) { ctx.log.info(默認處理); }); const crawler new HttpCrawler({ requestHandler: router }); await crawler.run();它有三個重載傳入路由表RouterRoutes、傳入Recordstring, UserData的 userData 映射、或傳入RouteSchemas生成帶類型推導的路由配合RoutesFromSchemas。這樣可以在請求的userData.label上分發不同處理邏輯避免在單個 handler 里堆疊if/else。FileDownload并行文件下載爬蟲定位與示例FileDownloadfile-download.ts繼承BasicCrawlerFileDownloadCrawlingContext使用普通 HTTP 請求并行下載文件速度快且省帶寬但不解析內容——需要從文件中提取數據時應改用CheerioCrawler/PuppeteerCrawler/PlaywrightCrawler。倉庫示例 docs/examples/file_download.ts 展示了從 Key-Value Store 保存二進制文件的用法import { FileDownload } from crawlee; const crawler new FileDownload({ async requestHandler({ request, response, contentType, getKeyValueStore }) { const url new URL(request.url); const kvs await getKeyValueStore(); await kvs.setValue(url.pathname.replace(/\//g, _), response.body, { contentType: contentType.type }); }, }); await crawler.addRequests([ https://pdfobject.com/pdf/sample.pdf, https://download.blender.org/peach/bigbuckbunny_movies/BigBuckBunny_320x180.mp4, https://upload.wikimedia.org/wikipedia/commons/c/c8/Example.ogg, ]); await crawler.run();上下文與管線FileDownloadCrawlingContextUserDatafile-download.ts暴露requestLoadedRequest、responseResponse、contentType{ type, encoding }三個成員。在buildContextPipeline中下載動作會通過httpClient.sendRequest發起請求并用parseContentTypeFromResponse解析類型用trackBodyConsumption把原始 body 經TransformStream包裝成新的ResponseWithUrl同時得到bodyDrainedPromise在管線 cleanup 階段若 body 未被消費則調用response.body.cancel()釋放底層連接并等待bodyDrained完成file-download.ts——確保下載連接的資源得到及時回收。流式下載輔助工具MinimumSpeedStream 與 ByteCounterStream這兩個Transform流file-download.ts是為處理下載數據流場景設計的可接入任意 Node.js 流管道。MinimumSpeedStream最低下載速度保護MinimumSpeedStream({ minSpeedKbps, historyLengthMs 10e3, checkProgressInterval 5e3 })每checkProgressInterval毫秒檢查一次統計最近historyLengthMs毫秒內收到的字節數若平均速度低于minSpeedKbpsKB/s即totalBytes / 1024 / elapsed minSpeedKbps則觸發error事件Stream speed too slow, aborting...并清除定時器。典型用途是慢速網絡下的下載超時保護。注意stream變量在checkInterval回調中被引用屬閉包延遲引用流創建后定時器才會真正開始工作。ByteCounterStream下載進度統計ByteCounterStream({ logTransferredBytes, loggingInterval 5000 })統計流經的數據字節數每loggingInterval毫秒調用一次logTransferredBytes(bytes)匯報累計字節數流結束時flush再做最后一次匯報。典型用途是打印大文件下載進度。兩者均為純函數式工廠返回 Node.jsTransform可自由組合例如先經過ByteCounterStream記錄進度再經過MinimumSpeedStream做限速保護最后寫入本地文件。配套閱讀與進一步探索若想繼續深入建議按以下路徑閱讀倉庫源碼與測試核心實現packages/http-crawler/src/internals/http-crawler.ts、packages/http-crawler/src/internals/file-download.ts、packages/http-crawler/src/internals/utils.ts可運行示例docs/examples/http_crawler.ts對應講解頁 docs/examples/http_crawler.mdx、docs/examples/file_download.ts行為測試test/core/crawlers/http_crawler.test.ts覆蓋并發調優、parseWithCheerio、Content-Type 解析、additionalMimeTypes、navigationTimeoutSecs等HTTP 客戶端架構docs/guides/http-clients.mdxBaseHttpClient接口與 impit / got-scraping 客戶端切換依賴的基礎能力BasicCrawler、ContextPipeline、ConcurrencySystem均位于 packages/basic-crawler 與 packages/core小結crawlee/http是 Crawlee 體系中輕量、高速、低資源占用的一翼HttpCrawler用純 HTTP 請求完成 HTML/JSON 抓取通過共享導航窗口的超時模型、編碼探測與回退、MIME 白名單、429 限流退避、會話 Cookie 回寫和可選的 Cheerio 解析在無需瀏覽器的情況下提供可靠的并發爬取能力FileDownload則把同一套管線復用到任意文件的并行下載上MinimumSpeedStream與ByteCounterStream補齊了大文件下載場景下的速度保護與進度可視化。當目標站點需要執行 JavaScript 時再切換到PuppeteerCrawler/PlaywrightCrawler即可形成完整的抓取方案矩陣。【免費下載鏈接】crawleeCrawlee—A web scraping and browser automation library for Node.js to build reliable crawlers. In JavaScript and TypeScript. Extract data for AI, LLMs, RAG, or GPTs. Download HTML, PDF, JPG, PNG, and other files from websites. Works with Puppeteer, Playwright, Cheerio, JSDOM, and raw HTTP. Both headful and headless mode. With proxy rotation.項目地址: https://gitcode.com/GitHub_Trending/cr/crawlee創作聲明:本文部分內容由AI輔助生成(AIGC),僅供參考