DEV Community

Cover image for How to automate an image-based captcha solution in JavaScript
Dzmitry
Dzmitry

Posted on

1

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

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more