How to automate an image-based captcha solution in JavaScript
Dzmitry
Posted on November 6, 2023
This article describes how to automate image-based captcha solving in JavaScript using Puppeteer and the 2captcha service. Puppeteer is a Node.js library used for automation. 2captcha is a service used to solve captchas. To interact with the 2captcha service, the 2captcha-ts library is used.
Algorithm of actions:
- Open the page in Puppeteer and save the captcha image
- Sending the captcha to the service
- We get the answer to the captcha
- We use the received answer on the page
Step #1 - Open the page in Puppeteer and save the captcha image
For example, let’s open a demo page with a captcha image and save the captcha image:
// Open page
await page.goto("https://2captcha.com/demo/normal");
await page.waitForSelector('img[alt="normal captcha example"]');
const element = await page.$('img[alt="normal captcha example"]');
// Save captcha
await element.screenshot({ path: "./image_captcha.png" });
Step #2 - Sending the captcha to the service
const getCaptchaAnswer = async () => {
try {
const base64Captcha = fs.readFileSync("./image_captcha.png", "base64");
// Sending captcha to 2captcha.com service
const res = await solver.imageCaptcha({
body: base64Captcha,
});
return res.data;
} catch (err) {
console.log(err);
}
};
Step #3 - We get the answer to the captcha
const captchaAnswer = await getCaptchaAnswer();
console.log("captchaAnswer:" + captchaAnswer);
Step #4 -We use the received answer on the page
// Typing the received answer into the answer field
await page.type("#simple-captcha-field", captchaAnswer, { delay: 500 });
await page.evaluate(() => {
// Click on 'check' button
document.querySelector("button[type=submit]").click();
});
Full code example available on GitHub
💖 💪 🙅 🚩
Dzmitry
Posted on November 6, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.