Apify là một nền tảng quét đám mây chạy các diễn viên Crawlee. Dưới đây là cách thêm giải pháp CaptchaAI CAPTCHA cho diễn viên Apify của bạn.
Thiết lập diễn viên
Lược đồ đầu vào
{
"title": "CAPTCHA Scraper Input",
"type": "object",
"properties": {
"startUrls": {
"title": "Start URLs",
"type": "array",
"editor": "requestListSources"
},
"captchaaiApiKey": {
"title": "CaptchaAI API Key",
"type": "string",
"isSecret": true
},
"maxConcurrency": {
"title": "Max Concurrency",
"type": "integer",
"default": 3
}
},
"required": ["startUrls", "captchaaiApiKey"]
}
Mã diễn viên
const { Actor } = require('apify');
const { PlaywrightCrawler } = require('crawlee');
Actor.main(async () => {
const input = await Actor.getInput();
const { startUrls, captchaaiApiKey, maxConcurrency = 3 } = input;
const solver = new CaptchaAISolver(captchaaiApiKey);
const crawler = new PlaywrightCrawler({
maxConcurrency,
requestHandlerTimeoutSecs: 180,
async requestHandler({ request, page, log }) {
await page.goto(request.url, { waitUntil: 'networkidle' });
// Check for CAPTCHA
const sitekey = await page.evaluate(() => {
const el = document.querySelector('[data-sitekey]');
return el ? el.getAttribute('data-sitekey') : null;
});
if (sitekey) {
log.info(`Solving CAPTCHA on ${request.url}`);
const token = await solver.solve(sitekey, request.url);
// Inject and submit
await page.evaluate((t) => {
document.querySelector('[name="g-recaptcha-response"]').value = t;
const cb = document.querySelector('.g-recaptcha')?.getAttribute('data-callback');
if (cb && window[cb]) window[cb](t);
}, token);
await page.click('button[type="submit"]');
await page.waitForNavigation({ timeout: 15000 });
}
// Extract data
const title = await page.title();
const items = await page.$$eval('.item', els =>
els.map(el => ({
name: el.querySelector('.name')?.textContent?.trim(),
price: el.querySelector('.price')?.textContent?.trim(),
url: el.querySelector('a')?.href,
}))
);
// Push to Apify dataset
await Actor.pushData({
url: request.url,
title,
items,
scrapedAt: new Date().toISOString(),
});
log.info(`Scraped ${items.length} items from ${request.url}`);
},
});
await crawler.run(startUrls);
});
class CaptchaAISolver {
constructor(apiKey) {
this.apiKey = apiKey;
}
async solve(sitekey, pageurl) {
const params = new URLSearchParams({
key: this.apiKey,
method: 'userrecaptcha',
googlekey: sitekey,
pageurl: pageurl,
json: '1',
});
const submitResp = await fetch('https://ocr.captchaai.com/in.php', {
method: 'POST',
body: params,
});
const submitResult = await submitResp.json();
if (submitResult.status !== 1) {
throw new Error(`Submit: ${submitResult.request}`);
}
const taskId = submitResult.request;
await new Promise(r => setTimeout(r, 15000));
for (let i = 0; i < 24; i++) {
const pollResp = await fetch(
`https://ocr.captchaai.com/res.php?key=${this.apiKey}&action=get&id=${taskId}&json=1`
);
const result = await pollResp.json();
if (result.status === 1) return result.request;
if (result.request !== 'CAPCHA_NOT_READY') {
throw new Error(`Solve: ${result.request}`);
}
await new Promise(r => setTimeout(r, 5000));
}
throw new Error('Timeout');
}
}
Biến môi trường trên Apify
Lưu trữ khóa CaptchaAI của bạn một cách an toàn:
- Chuyển đến Cài đặt diễn viên – Biến môi trường
- Thêm:
CAPTCHAAI_API_KEY= khóa của bạn (đánh dấu là bí mật) - Truy cập bằng mã:
process.env.CAPTCHAAI_API_KEY
// Alternative: use env var instead of input
const apiKey = input.captchaaiApiKey || process.env.CAPTCHAAI_API_KEY;
Proxy Apify + CaptchaAI
const crawler = new PlaywrightCrawler({
proxyConfiguration: await Actor.createProxyConfiguration({
groups: ['RESIDENTIAL'],
}),
// ... rest of config
});
Câu hỏi thường gặp
Tôi có thể sử dụng CaptchaAI trên bậc miễn phí của Apify không?
Vâng. CaptchaAI là lệnh gọi API bên ngoài hoạt động trên mọi gói Apify. Chi phí của bạn là giá mỗi lần giải của CaptchaAI cộng với chi phí điện toán của Apify.
Tôi nên sử dụng proxy Apify hay tham số proxy của CaptchaAI?
Sử dụng proxy Apify để loại bỏ các yêu cầu và CaptchaAI không cần proxy để giải quyết. Đây là cách tiếp cận hiệu quả nhất về chi phí cho hầu hết các trường hợp sử dụng.
Làm cách nào để xử lý thời gian chờ của diễn viên Apify bằng tính năng giải CAPTCHA?
Đặt requestHandlerTimeoutSecs thành ít nhất 180 giây để có thời gian giải CAPTCHA.
Hướng dẫn liên quan
- Tích hợp Crawlee + CaptchaAI
- Xây dựng khung Scraping tùy chỉnh
Triển khai các tác nhân giải CAPTCHA —nhận CaptchaAI.