Node.js vượt trội về khối lượng công việc quét I/O-heavy. Khi các trang web mục tiêu phân phát CAPTCHA, API của CaptchaAI sẽ giải quyết chúng trong khi tập lệnh của bạn xử lý các yêu cầu HTTP. Hướng dẫn này bao gồm quy trình làm việc hoàn chỉnh bằng cách sử dụng axios và cổ vũ.
Yêu cầu
| Yêu cầu | Chi tiết |
|---|---|
| Node.js 16+ | Với npm |
| trục | npm install axios |
| cổ vũ | npm install cheerio |
| Khóa API CaptchaAI | Từcaptchaai.com |
Mô-đun bộ giải CaptchaAI
// captcha-solver.js
const axios = require("axios");
class CaptchaSolver {
constructor(apiKey) {
this.apiKey = apiKey;
this.baseUrl = "https://ocr.captchaai.com";
}
async _submit(params) {
params.key = this.apiKey;
const resp = await axios.get(`${this.baseUrl}/in.php`, { params });
if (!resp.data.startsWith("OK|")) {
throw new Error(`Submit error: ${resp.data}`);
}
return resp.data.split("|")[1];
}
async _poll(taskId, timeout = 300000) {
const deadline = Date.now() + timeout;
while (Date.now() < deadline) {
await new Promise((r) => setTimeout(r, 5000));
const resp = await axios.get(`${this.baseUrl}/res.php`, {
params: { key: this.apiKey, action: "get", id: taskId },
});
if (resp.data === "CAPCHA_NOT_READY") continue;
if (resp.data.startsWith("OK|")) return resp.data.split("|")[1];
throw new Error(`Solve error: ${resp.data}`);
}
throw new Error("Solve timed out");
}
async solveRecaptchaV2(siteKey, pageUrl) {
const taskId = await this._submit({
method: "userrecaptcha",
googlekey: siteKey,
pageurl: pageUrl,
});
return this._poll(taskId);
}
async solveRecaptchaV3(siteKey, pageUrl, action = "verify") {
const taskId = await this._submit({
method: "userrecaptcha",
googlekey: siteKey,
pageurl: pageUrl,
version: "v3",
action,
});
return this._poll(taskId);
}
async solveTurnstile(siteKey, pageUrl) {
const taskId = await this._submit({
method: "turnstile",
sitekey: siteKey,
pageurl: pageUrl,
});
return this._poll(taskId);
}
}
module.exports = CaptchaSolver;
Quét trang được bảo vệ bằng reCAPTCHA
const axios = require("axios");
const cheerio = require("cheerio");
const CaptchaSolver = require("./captcha-solver");
const solver = new CaptchaSolver("YOUR_API_KEY");
async function scrapeProtectedPage(url) {
// Step 1: Load the page
const { data: html } = await axios.get(url, {
headers: {
"User-Agent":
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
},
});
const $ = cheerio.load(html);
// Step 2: Extract site key
const siteKey = $(".g-recaptcha").attr("data-sitekey");
if (!siteKey) {
console.log("No CAPTCHA found, page loaded directly");
return html;
}
console.log("Site key found:", siteKey);
// Step 3: Solve the CAPTCHA
const token = await solver.solveRecaptchaV2(siteKey, url);
console.log("Token received:", token.substring(0, 50));
// Step 4: Submit with the token
const result = await axios.post(
url,
new URLSearchParams({
"g-recaptcha-response": token,
q: "search query",
}),
{
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"User-Agent":
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
},
}
);
return result.data;
}
Quét nhiều trang đồng thời
async function scrapePages(urls, siteKey, concurrency = 3) {
const results = [];
const queue = [...urls];
const worker = async () => {
while (queue.length > 0) {
const url = queue.shift();
try {
const token = await solver.solveRecaptchaV2(siteKey, url);
const { data } = await axios.post(
url,
new URLSearchParams({ "g-recaptcha-response": token }),
{
headers: {
"User-Agent":
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
},
}
);
results.push({ url, data, success: true });
console.log(`Scraped: ${url}`);
} catch (err) {
results.push({ url, error: err.message, success: false });
console.error(`Failed: ${url} - ${err.message}`);
}
}
};
// Run workers concurrently
const workers = Array(concurrency)
.fill(null)
.map(() => worker());
await Promise.all(workers);
return results;
}
// Usage
const urls = [
"https://example.com/page/1",
"https://example.com/page/2",
"https://example.com/page/3",
];
const results = await scrapePages(urls, "6Le-wvkS...", 3);
Xử lý cookie và phiên
Sử dụng axios với khả năng duy trì cookie cho các trang web yêu cầu cookie phiên:
const { wrapper } = require("axios-cookiejar-support");
const { CookieJar } = require("tough-cookie");
const jar = new CookieJar();
const client = wrapper(
axios.create({
jar,
headers: {
"User-Agent":
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
},
})
);
async function scrapeWithSession(url, siteKey) {
// Initial page load sets cookies
await client.get(url);
// Solve CAPTCHA
const token = await solver.solveRecaptchaV2(siteKey, url);
// Submit with maintained cookies
const result = await client.post(
url,
new URLSearchParams({ "g-recaptcha-response": token })
);
return result.data;
}
Phân tích kết quả với Cheerio
function parseResults(html) {
const $ = cheerio.load(html);
const items = [];
$(".result-item").each((_, el) => {
items.push({
title: $(el).find(".title").text().trim(),
url: $(el).find("a").attr("href"),
description: $(el).find(".description").text().trim(),
});
});
return items;
}
Khắc phục sự cố
| Vấn đề | Nguyên nhân | Cách xử lý |
|---|---|---|
CAPTCHA_NOT_READY lặp vô thời hạn |
Khóa trang sai hoặc giải quyết chậm | Xác minh khóa trang web; tăng thời gian chờ |
403 Forbidden trên BÀI ĐĂNG |
Thiếu cookie hoặc tiêu đề | Sử dụng cookie phiên; thêm tiêu đề Referer |
| Cheerio không thể tìm thấy các yếu tố | Nội dung động | Sử dụng Puppeteer cho các trang web được hiển thị bằng JS |
ECONNREFUSED |
Tỷ lệ bị giới hạn bởi trang web mục tiêu | Thêm độ trễ; xoay proxy |
Câu hỏi thường gặp
Khi nào tôi nên sử dụng Puppeteer thay vì axios?
Sử dụng axios + cổ vũ khi trang đích trả về HTML với các lần gửi biểu mẫu tiêu chuẩn. Sử dụng Puppeteer khi trang web yêu cầu thực thi JavaScript, hiển thị động hoặc tương tác phức tạp của người dùng.
Tôi có thể giải nhiều CAPTCHA cùng một lúc không?
Vâng. Gửi đồng thời nhiều tác vụ CAPTCHA tới CaptchaAI và thăm dò ý kiến cho từng kết quả. Ví dụ cạo đồng thời ở trên thể hiện mẫu này.
Làm cách nào để xử lý các trang web được Cloudflare bảo vệ?
Nếu trang web sử dụng Turnstile, hãy sử dụng solver.solveTurnstile(). Đối với các trang thử thách Cloudflare đầy đủ, hãy sử dụngGiải quyết Cloudflare Challengetrả về cookie <staging-session-cookie>.
Hướng dẫn liên quan
- Puppeteer giải CAPTCHA bằng Node.js
- Quét CAPTCHA bằng Python
- Xoay vòng proxy để quét CAPTCHA