使用 apify-client 套件將 Apify 整合到現有的 JavaScript/TypeScript 或 Python 應用程式中。當需要透過 Apify API 為現有應用程式加入網頁爬取、自動化或資料擷取功能時使用。
Apify SDK 整合
將 Apify Actor 執行功能加入現有應用程式。本技能涵蓋適用於 JS/TS 和 Python 的 apify-client 套件,以及其他語言的 REST API。
何時使用此技能
- 為現有應用程式加入網頁爬取或自動化功能
- 從應用程式程式碼中以程式方式呼叫 Apify Actor
- 建構使用 Apify 作為後端服務的產品
- 將 Actor 結果整合到資料管線中
重要:套件命名
apify-client是用於從應用程式呼叫 Actor 的 API 用戶端。
apify是用於建構 Actor 的 SDK(不適用於此使用案例)。請務必安裝
apify-client。進行整合工作時,絕對不要安裝apify。
前置需求
使用者需要一個 APIFY_TOKEN。請引導他們前往 主控台 > 設定 > 整合(https://console.apify.com/settings/integrations)建立一個。如果他們沒有帳戶:https://console.apify.com/sign-up(免費,無需信用卡)。
安全地儲存 token — 使用環境變數或機密管理工具,切勿寫死在程式碼中。
尋找合適的 Actor
在撰寫整合程式碼之前,先找到符合使用者需求的 Actor。如果可用,請使用 MCP 工具:
search-actors— 依關鍵字搜尋 Apify Storefetch-actor-details— 取得 Actor 的輸入結構、輸出格式和定價
或者瀏覽 https://apify.com/store。在任何 Actor 的 Store URL 後加上 .md,即可取得其 Markdown 格式的文件。
JavaScript / TypeScript
安裝
npm install apify-client
同步執行(等待結果)
import { ApifyClient } from 'apify-client';
const client = new ApifyClient({ token: process.env.APIFY_TOKEN });
const run = await client.actor('apify/web-scraper').call({
startUrls: [{ url: 'https://example.com' }],
maxPagesPerCrawl: 10,
});
const { items } = await client.dataset(run.defaultDatasetId).listItems();
.call() 會阻塞直到 Actor 完成。適用於短時間執行的 Actor(幾分鐘內)。
非同步執行(啟動後再輪詢/取回)
const run = await client.actor('apify/web-scraper').start({
startUrls: [{ url: 'https://example.com' }],
});
// 輪詢直到完成
const finishedRun = await client.run(run.id).waitForFinish();
// 取回結果
const { items } = await client.dataset(finishedRun.defaultDatasetId).listItems();
對於長時間執行的 Actor,或需要立即取得 run ID 時,請使用 .start() + .waitForFinish()。
取回結果
// 資料集項目(來自 pushData 的結構化資料)
const { items } = await client.dataset(run.defaultDatasetId).listItems({
limit: 100,
offset: 0,
});
// 鍵值儲存(檔案、螢幕截圖等)
const record = await client.keyValueStore(run.defaultKeyValueStoreId).getRecord('OUTPUT');
錯誤處理
try {
const run = await client.actor('apify/web-scraper').call(input);
if (run.status !== 'SUCCEEDED') {
const log = await client.log(run.id).get();
throw new Error(`Actor failed with status ${run.status}: ${log}`);
}
const { items } = await client.dataset(run.defaultDatasetId).listItems();
} catch (error) {
if (error.message?.includes('not found')) {
// Actor ID 錯誤或 Actor 已被刪除
} else if (error.statusCode === 401) {
// APIFY_TOKEN 無效或遺失
}
throw error;
}
Python
安裝
pip install apify-client
同步執行
from apify_client import ApifyClient
import os
client = ApifyClient(token=os.environ['APIFY_TOKEN'])
run = client.actor('apify/web-scraper').call(run_input={
'startUrls': [{'url': 'https://example.com'}],
'maxPagesPerCrawl': 10,
})
items = client.dataset(run['defaultDatasetId']).list_items().items
非同步執行
run = client.actor('apify/web-scraper').start(run_input={
'startUrls': [{'url': 'https://example.com'}],
})
# 輪詢直到完成
finished_run = client.run(run['id']).wait_for_finish()
items = client.dataset(finished_run['defaultDatasetId']).list_items().items
非同步用戶端(asyncio)
from apify_client import ApifyClientAsync
client = ApifyClientAsync(token=os.environ['APIFY_TOKEN'])
run = await client.actor('apify/web-scraper').call(run_input={
'startUrls': [{'url': 'https://example.com'}],
})
items = (await client.dataset(run['defaultDatasetId']).list_items()).items
REST API(任何語言)
對於沒有官方用戶端的語言,可以直接使用 REST API。
啟動執行
POST https://api.apify.com/v2/acts/{actorId}/runs
Authorization: Bearer <APIFY_TOKEN>
Content-Type: application/json
{ "startUrls": [{ "url": "https://example.com" }] }
取得執行狀態
GET https://api.apify.com/v2/acts/{actorId}/runs/{runId}
Authorization: Bearer <APIFY_TOKEN>
取得資料集項目
GET https://api.apify.com/v2/datasets/{datasetId}/items?format=json
Authorization: Bearer <APIFY_TOKEN>
完整 API 參考:https://docs.apify.com/api/v2
最佳實務
- 設定逾時: 在 Actor 輸入中傳遞
timeoutSecs,或對.call()使用waitSecs,以避免無限期等待。 - 分頁處理大型資料集: 取回資料集項目時使用
limit和offset。預設限制為 250K 個項目。 - 重複使用用戶端: 建立一個
ApifyClient實例並在多次呼叫中重複使用。 - 處理 Actor 特定的輸入: 每個 Actor 都有自己的輸入結構。使用
fetch-actor-detailsMCP 工具,或在 Actor 的 Store URL 後加上.md,以在建構輸入前取得結構。
文件
- Apify API 用戶端(JS):https://docs.apify.com/api/client/js
- Apify API 用戶端(Python):https://docs.apify.com/api/client/python
- REST API 參考:https://docs.apify.com/api/v2
- Apify 文件(LLM 友善):https://docs.apify.com/llms.txt
- Apify 文件(完整版):https://docs.apify.com/llms-full.txt
如果 Apify MCP 伺服器可用,請在開發期間使用 search-apify-docs 和 fetch-apify-docs 工具進行上下文相關的文件查詢。






