利用百度OCR实现验证码自动识别

时间:2023-03-09 04:49:18
利用百度OCR实现验证码自动识别

在爬取网站的时候都遇到过验证码,那么我们有什么方法让程序自动的识别验证码呢?其实网上已有很多打码平台,但是这些都是需要money。但对于仅仅爬取点数据而接入打码平台实属浪费。所以百度免费ocr正好可以利用。(每天500次免费)

1、注册百度账号、百度云管理中心创建应用、生成AppKey、SecretKey(程序调用接口是要生成access_token)
利用百度OCR实现验证码自动识别

利用百度OCR实现验证码自动识别

2、利用AppKey、SecretKey生成access_token
向授权服务地址https://aip.baidubce.com/oauth/2.0/token发送请求(推荐使用POST)并在URL中带上以下参数:
grant_type: 必须参数,固定为client_credentials;
client_id: 必须参数,应用的API Key;
client_secret: 必须参数,应用的Secret Key
代码如下:

/**
* 获取AccessToken
* 百度开发
* AppId:
* APIKey:
* SecretKey:
*
* @return
*/
public static String getAccessToken() {
String accessToken = "";
HttpRequestData httpRequestData = new HttpRequestData();
HashMap<String, String> params = new HashMap<>();
params.put("grant_type", "client_credentials");
params.put("client_id", "xxxxxx");
params.put("client_secret", "xxxxxx");
httpRequestData.setRequestMethod("GET");
httpRequestData.setParams(params);
httpRequestData.setRequestUrl("https://aip.baidubce.com/oauth/2.0/token");
HttpResponse response = HttpClientUtils.execute(httpRequestData);
String json = "";
try {
json = IOUtils.toString(response.getEntity().getContent());
} catch (IOException e) {
e.printStackTrace();
}
if (response.getStatusLine().getStatusCode() == 200) {
JSONObject jsonObject = JSONObject.parseObject(json);
if (jsonObject != null && !jsonObject.isEmpty()) {
accessToken = jsonObject.getString("access_token");
}
}
return accessToken;
}

3、请求百度ocr通用文字识别API(下面以百度通用识别api识别为例)
请求API的URL https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic
请求方法 POST
请求URL参数 access_token
请求头 (Header) Content-Type application/x-www-form-urlencoded
Body中放置请求参数,主要参数详情如下:

  • image : 图像数据,base64编码,要求base64编码后大小不超过4M,最短边至少15px,最长边最大4096px,支持jpg/png/bmp格式,当image字段存在时url字段失效
  • url : 图片完整URL,URL长度不超过1024字节,URL对应的图片base64编码后大小不超过4M,最短边至少15px,最长边最大4096px,支持jpg/png/bmp格式,当image字段存在时url字段失效
/**
* 获取识别验证码
* @param imageUrl
* @return
*/
public static String OCRVCode(String imageUrl){
String VCode = ""; if (StringUtils.isBlank(ACCESS_TOKEN)) {
logger.error("accessToken为空");
return VCode;
}
OCRUrl = OCRUrl + "?access_token=" + ACCESS_TOKEN; HashMap<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/x-www-form-urlencoded"); HashMap<String, String> params = new HashMap<>();
imageUrl = ImageBase64ToStringUtils.imageToStringByBase64(imageUrl);
params.put("image", imageUrl); HttpRequestData httpRequestData = new HttpRequestData();
httpRequestData.setHeaders(headers);
httpRequestData.setRequestMethod("post");
httpRequestData.setParams(params);
httpRequestData.setRequestUrl(OCRUrl);
HttpResponse response = HttpClientUtils.execute(httpRequestData);
String json = "";
if (response.getStatusLine().getStatusCode() == 200) {
try {
json = IOUtils.toString(response.getEntity().getContent());
JSONObject jsonObject = JSONObject.parseObject(json);
JSONArray wordsResult = jsonObject.getJSONArray("words_result");
VCode = wordsResult.getJSONObject(0).getString("words");
} catch (IOException e) {
logger.error("请求识别失败!", e);
}
}
return VCode;
}

对图片进行base64编码字符

/**
* 将本地图片进行Base64位编码
* @param imageFile
* @return
*/
public static String encodeImgageToBase64(String imageFile) {
// 其进行Base64编码处理
byte[] data = null;
// 读取图片字节数组
try {
InputStream in = new FileInputStream(imageFile);
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
e.printStackTrace();
} // 对字节数组Base64编码
return Base64Util.encode(data);
}

4、返回结果以json方式返回

{
"log_id": 2471272194,
"words_result_num": 2,
"words_result":
[
{"words": " TSINGTAO"},
{"words": "青島睥酒"}
]
}

项目github地址:https://github.com/xwlmdd/ipProxyPool
注:ocr图片识别模块在这个项目里的一个工具类