使用 JavaScript (Node.js) 实现验证码识别与自动化登录
- 安装所需依赖
首先,确保你已经安装了 Node.js。然后,使用 npm 安装所需的库:
bash
npm install axios jimp tesseract.js
2. 下载验证码图片
使用 axios 下载验证码图片并保存到本地:
更多内容联系1436423940
javascript
const fs = require('fs');
const axios = require('axios');
async function downloadCaptcha(url, savePath) {
const response = await axios.get(url, { responseType: 'arraybuffer' });
fs.writeFileSync(savePath, response.data);
console.log(验证码图片已保存为 ${savePath}
);
}
downloadCaptcha('https://captcha7.scrape.center/captcha.png', 'captcha.png');
3. 图像处理和 OCR 识别
使用 jimp 和 tesseract.js 进行图像处理和 OCR 识别:
javascript
const Jimp = require('jimp');
const Tesseract = require('tesseract.js');
async function recognizeCaptcha(imagePath) {
const image = await Jimp.read(imagePath);
image.threshold({ max: 128 }); // 转为黑白图像
const { data: { text } } = await Tesseract.recognize(image.bitmap, 'eng');
console.log(`识别结果: ${text.trim()}`);
return text.trim();
}
recognizeCaptcha('captcha.png');
4. 自动化登录
使用 axios 发送 POST 请求,模拟登录操作,并传递用户名、密码和识别出的验证码:
javascript
async function login(username, password, captcha) {
const url = 'https://captcha7.scrape.center/login';
const response = await axios.post(url, {
username,
password,
captcha
});
if (response.status === 200) {
console.log('登录成功');
} else {
console.log(`登录失败: ${response.status}`);
}
}
5. 主程序
整合上述代码,创建主程序:
javascript
(async () => {
const captchaUrl = 'https://captcha7.scrape.center/captcha.png';
const captchaPath = 'captcha.png';
// 下载验证码
await downloadCaptcha(captchaUrl, captchaPath);
// 识别验证码
const captchaText = await recognizeCaptcha(captchaPath);
// 登录
await login('admin', 'admin', captchaText);
})();