网格图像验证码呈现 3×3 或 4×4 网格,并带有“选择所有带有交通信号灯的方块”等指令。本教程展示了如何使用 Node.js 解决这些问题CaptchaAI和Puppeteer。
先决条件
| 物品 | 价值 |
|---|---|
| CaptchaAI API 密钥 | 从验证码网站 |
| Node.js | 14+ |
| 图书馆 | axios、puppeteer |
第 1 步:捕获网格图像
const puppeteer = require('puppeteer');
const fs = require('fs');
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://example.com/page-with-recaptcha');
// Switch to the reCAPTCHA challenge iframe
const frames = page.frames();
const challengeFrame = frames.find((f) => f.url().includes('recaptcha/api2/bframe'));
// Get the instruction text
const instruction = await challengeFrame.$eval(
'.rc-imageselect-desc-no-canonical',
(el) => el.textContent.trim()
);
// Screenshot the grid
const grid = await challengeFrame.$('.rc-imageselect-target');
await grid.screenshot({ path: 'grid.png' });
第二步:提交至CaptchaAI
const axios = require('axios');
const FormData = require('form-data');
const API_KEY = 'YOUR_API_KEY';
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const form = new FormData();
form.append('key', API_KEY);
form.append('method', 'post');
form.append('grid_size', '3x3');
form.append('img_type', 'recaptcha');
form.append('instructions', instruction);
form.append('json', '1');
form.append('file', fs.createReadStream('grid.png'));
const { data: submitData } = await axios.post('https://ocr.captchaai.com/in.php', form, {
headers: form.getHeaders(),
});
if (submitData.status !== 1) throw new Error(submitData.request);
const taskId = submitData.request;
console.log(`Task submitted: ${taskId}`);
第 3 步:民意调查解决方案
await sleep(5000);
let cellsToClick;
for (let i = 0; i < 30; i++) {
const { data: pollData } = await axios.get('https://ocr.captchaai.com/res.php', {
params: { key: API_KEY, action: 'get', id: taskId, json: 1 },
});
if (pollData.status === 1) {
cellsToClick = JSON.parse(pollData.request);
console.log('Click cells:', cellsToClick);
break;
}
if (pollData.request !== 'CAPCHA_NOT_READY') {
throw new Error(pollData.request);
}
await sleep(5000);
}
第四步:点击正确的图块
const tiles = await challengeFrame.$$('.rc-imageselect-tile');
for (const cellNum of cellsToClick) {
await tiles[cellNum - 1].click();
await sleep(300);
}
// Click verify
await challengeFrame.click('#recaptcha-verify-button');
console.log(`Solved: clicked tiles ${JSON.stringify(cellsToClick)}`);
await browser.close();
预期输出:
Click cells: [1, 3, 6, 9]
Solved: clicked tiles [1,3,6,9]
常问问题
这适用于 4×4 网格吗?
是的。将请求参数中的“grid_size”设置为“4x4”。
我可以使用 Playwright 代替 Puppeteer 吗?
是的。 CaptchaAI API 调用是相同的 - 只是浏览器自动化代码发生了变化。
如果验证码刷新为新图像怎么办?
一些 reCAPTCHA 挑战会加载新的图块。您可能需要为每一轮重新捕获并提交。