How to automate an image-based captcha solution in JavaScript

dzmitry

Dzmitry

Posted on November 6, 2023

How to automate an image-based captcha solution in JavaScript

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:

  1. Open the page in Puppeteer and save the captcha image
  2. Sending the captcha to the service
  3. We get the answer to the captcha
  4. 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" });
Enter fullscreen mode Exit fullscreen mode

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);
  }
};
Enter fullscreen mode Exit fullscreen mode

Step #3 - We get the answer to the captcha

const captchaAnswer = await getCaptchaAnswer();
console.log("captchaAnswer:" + captchaAnswer);
Enter fullscreen mode Exit fullscreen mode

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();
});
Enter fullscreen mode Exit fullscreen mode

Full code example available on GitHub

💖 💪 🙅 🚩
dzmitry
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.

Related