Bạn không cần Puppeteer hoặc Playwright để giải CAPTCHA. Với Axios và CaptchaAI, bạn có thể giải quyết reCAPTCHA, Turnstile và CAPTCHA hình ảnh bằng cách sử dụng các yêu cầu HTTP thuần túy - không cần tốn chi phí trình duyệt.
Yêu cầu
| Yêu cầu | Chi tiết |
|---|---|
| Node.js | 16+ |
| trục | 1.x |
| Khóa API CaptchaAI | Nhận một cái ở đây |
npm install axios
Khách hàng CaptchaAI
const axios = require("axios");
class CaptchaAI {
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 });
const text = resp.data;
if (!String(text).startsWith("OK|")) {
throw new Error(`Submit failed: ${text}`);
}
return String(text).split("|")[1];
}
async poll(taskId, timeoutMs = 300000) {
const deadline = Date.now() + timeoutMs;
const params = { key: this.apiKey, action: "get", id: taskId };
while (Date.now() < deadline) {
await new Promise((r) => setTimeout(r, 5000));
const resp = await axios.get(`${this.baseUrl}/res.php`, { params });
const text = String(resp.data);
if (text === "CAPCHA_NOT_READY") continue;
if (text.startsWith("OK|")) return text.split("|").slice(1).join("|");
throw new Error(`Solve failed: ${text}`);
}
throw new Error(`Timeout after ${timeoutMs}ms for task ${taskId}`);
}
async solve(params, timeoutMs = 300000) {
const taskId = await this.submit(params);
return this.poll(taskId, timeoutMs);
}
async getBalance() {
const resp = await axios.get(`${this.baseUrl}/res.php`, {
params: { key: this.apiKey, action: "getbalance" },
});
return parseFloat(resp.data);
}
}
module.exports = CaptchaAI;
Giải reCAPTCHA v2 (Không có trình duyệt)
const CaptchaAI = require("./captchaai");
async function main() {
const solver = new CaptchaAI(process.env.CAPTCHAAI_API_KEY);
// Solve the CAPTCHA without opening any browser
const token = await solver.solve({
method: "userrecaptcha",
googlekey: "6Le-wvkS...",
pageurl: "https://staging.example.com/qa-login",
});
// Submit form with the token using Axios
const resp = await axios.post("https://staging.example.com/qa-login", {
username: "user",
password: "pass",
"g-recaptcha-response": token,
});
console.log(`Login response: ${resp.status}`);
}
main().catch(console.error);
Giải quyết Turnstile (Không có trình duyệt)
const token = await solver.solve({
method: "turnstile",
sitekey: "0x4AAAAA...",
pageurl: "https://example.com",
});
// Submit with Turnstile token
const resp = await axios.post("https://example.com/api/verify", {
"cf-turnstile-response": token,
data: "payload",
});
Giải CAPTCHA hình ảnh
const fs = require("fs");
const imageBuffer = fs.readFileSync("captcha.png");
const imageB64 = imageBuffer.toString("base64");
const text = await solver.solve({
method: "base64",
body: imageB64,
});
console.log(`CAPTCHA text: ${text}`);
// Submit form with solved text
const resp = await axios.post("https://example.com/verify", {
captcha: text,
other_data: "value",
});
Quy trình cạo đầy đủ
Quét trang được bảo vệ bằng CAPTCHA mà không cần bất kỳ trình duyệt nào:
const CaptchaAI = require("./captchaai");
const axios = require("axios");
const cheerio = require("cheerio");
async function scrapeProtectedPage(url) {
const solver = new CaptchaAI(process.env.CAPTCHAAI_API_KEY);
// Step 1: Fetch the page
const page = await axios.get(url);
const $ = cheerio.load(page.data);
// Step 2: Extract the reCAPTCHA site key
const siteKey = $(".g-recaptcha").attr("data-sitekey");
if (!siteKey) {
console.log("No CAPTCHA found, returning page content");
return page.data;
}
// Step 3: Solve the CAPTCHA
console.log(`Solving CAPTCHA for ${url}...`);
const token = await solver.solve({
method: "userrecaptcha",
googlekey: siteKey,
pageurl: url,
});
// Step 4: Submit form with token
const formAction = $("form").attr("action") || url;
const formData = {};
$("form input").each((_, el) => {
const name = $(el).attr("name");
const value = $(el).attr("value") || "";
if (name) formData[name] = value;
});
formData["g-recaptcha-response"] = token;
const result = await axios.post(formAction, new URLSearchParams(formData), {
headers: { "Content-Type": "application/x-www-form-urlencoded" },
});
return result.data;
}
scrapeProtectedPage("https://example.com/data")
.then((data) => console.log("Success:", typeof data))
.catch(console.error);
Giải đồng thời
async function solveBatch(urls, siteKey) {
const solver = new CaptchaAI(process.env.CAPTCHAAI_API_KEY);
const promises = urls.map(async (url) => {
try {
const token = await solver.solve({
method: "userrecaptcha",
googlekey: siteKey,
pageurl: url,
});
return { url, token, error: null };
} catch (error) {
return { url, token: null, error: error.message };
}
});
const results = await Promise.all(promises);
const solved = results.filter((r) => r.token);
console.log(`Solved ${solved.length}/${urls.length}`);
return results;
}
Khắc phục sự cố
| Lỗi | nguyên nhân | sửa chữa |
|---|---|---|
AxiosError: getaddrinfo ENOTFOUND |
sự cố DNS | Kiểm tra kết nối mạng |
Submit failed: ERROR_WRONG_USER_KEY |
Khóa API không hợp lệ | Xác minh khóa từ bảng điều khiển |
Submit failed: ERROR_ZERO_BALANCE |
Không có tiền | Thêm số dư vào tài khoản |
| Mã thông báo bị từ chối bởi trang web mục tiêu | Mã thông báo đã hết hạn | Gửi mã thông báo trong vòng 60 giây |
Câu hỏi thường gặp
Tại sao nên tránh sử dụng trình duyệt để giải CAPTCHA?
Trình duyệt tiêu thụ RAM 200-500 MB mỗi phiên bản. HTTP thuần túy với CaptchaAI sử dụng ~5MB. Điều này hiệu quả hơn 40-100 lần cho tự động hóa phía máy chủ.
Khi nào tôi vẫn cần trình duyệt?
Khi trang web yêu cầu hiển thị JavaScript cho nội dung. Đặc biệt đối với CAPTCHA, bạn không bao giờ cần trình duyệt - CaptchaAI xử lý việc giải quyết từ xa.
Tôi có thể sử dụng tìm nạp thay vì Axios không?
Vâng. Node.js 18+ bao gồm fetch gốc. Các tham số API CaptchaAI giống nhau.
Hướng dẫn liên quan
- Hướng dẫn quét Captcha Node.js
- Tích hợp HTTPX + CaptchaAI
- cURL + CaptchaAI CLI