Image recognition platform: https://www.juhe.cn/
Call the interface provided by the platform for image recognition
Note : Encode the local image in Base64
This class only uses these two methods: encodeImgageToBase64(), readContentFromPost().
Code:
package com.teamdev.jxbrowser.chromium.demoJD.yyzz;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io. File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection ;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import javax.imageio.ImageIO;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons. httpclient.methods.GetMethod;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import com.teamdev.jxbrowser.chromium.demoJD.yyzz.ImageUtils;
import sun.misc.BASE64Encoder;
public class ImageUtils {
/* *
*
Encode the local image to Base64
*
* @param imgUrl
* The url path of the image, such as xxx.jpg
* @return
*/ @SuppressWarnings
("deprecation")
public static String encodeImgageToBase64(File imageFile) {// Convert the image file to a byte array string and perform Base64 encoding on it
ByteArrayOutputStream outputStream = null;
try {
BufferedImage bufferedImage = ImageIO.read(imageFile);
outputStream = new ByteArrayOutputStream ();
ImageIO.write(bufferedImage, "jpg", outputStream);
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// Base64 for byte array Encode
BASE64Encoder encoder = new BASE64Encoder();
return java.net.URLEncoder.encode( encoder.encode(outputStream.toByteArray()));// Return Base64 encoded byte array string
}
/**
* Delete session file
* */
public static void DeleteSession() {
String path="F:\\yzm\\yzm.jpg";
File file =new File(path);
if (file.exists()) {
try {
file.delete();
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("faile delete session.txt ");
}
}
}
/**
* Download pictures
* */
public static void runDownLoad(String fileurl) {
// Construct URL
URL url ;
try {
url = new URL(fileurl);
// Open URL connection
URLConnection con = (URLConnection) url.openConnection();
// Get URL input stream
InputStream input = con.getInputStream();
// Set data buffer
byte[] bs = new byte[1024 * 2];
// The length of the read data
int len;
// The output file stream saves the picture to the local
String path1 = "F:\\yzm\\yzm.jpg";
File f = new File(path1);
// f.mkdirs();
OutputStream os = new FileOutputStream(path1);
while ((len = input.read(bs)) != -1) {
os.write(bs, 0, len) ;
}
os.close();
input.close();
} catch (MalformedURLException e) {
// TODO auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO auto-generated catch block
e.printStackTrace();
}
}
/**
* Send POST method request to specified URL
*
* @param url
* URL to send request
* @param param
* Request parameter, the request parameter should be in the form of name1=value1&name2=value2.
* The response result of the remote resource represented by @return
*/
/**
* Parse the verification code
* @throws Exception
* */
public static String readContentFromPost(String imgPath) throws IOException {
String str = ImageUtils.encodeImgageToBase64(new File(imgPath)) ;
URL postUrl = new URL("http://op.juhe.cn/vercode/index");
HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.connect();
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
String content = "codeType=8003&&image=&base64Str=" + str + "&dtype=&key=bdb9286128139fa1a61d8b7ca84ab171";
out.writeBytes(content);
out.flush();
out.close();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuilder sb=new StringBuilder();
while ((line = reader.readLine()) != null) {
System.out.println(line);
sb.append(line);
}
//{"reason":"成功的返回","result":"rahu","error_code":0}
String result=sb.toString().split("result\":\"")[1].split("\",")[0];
reader.close();
connection.disconnect();
return result;
}
//测试
public static void main(String[] args) throws IOException{
System.out.println(readContentFromPost("F:\\yzm\\yzm.jpg"));
}
}
==================================================================自己的代码
package com.teamdev.jxbrowser.chromium.demoJD.yyzz;
/**
* 抓取京东营业执照信息
* */
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.BrowserPreferences;
import com.teamdev.jxbrowser.chromium.JSValue;
import com.teamdev.jxbrowser.chromium.LoggerProvider;
import com.teamdev.jxbrowser.chromium.events.FinishLoadingEvent;
import com.teamdev.jxbrowser.chromium.events.LoadAdapter;
import com.teamdev.jxbrowser.chromium.swing.BrowserView;
public class jd_yyzz {
private static final Color White = null;
/**
*======== 主方法
* */
public static void main(String[] args) throws Exception {
//获取url,解析验证码
String shop_url =Get_Shop_url();
String html=saveImage(shop_url);
System.out.println(html);
}
/**
* ========Get url
* */
public static String Get_Shop_url(){
//Connect to the database here and query all urls
String shop_url="https ://mall.jd.com/showLicence-652046.html";
return shop_url;
}
/**
* Simulator screenshot (just intercept the verification code), call the interface, parse the verification code, fill in the input box and click to verify, return html data after successful verification
* */
public static String saveImage(String url){
LoggerProvider.getBrowserLogger().setLevel(Level.SEVERE);
LoggerProvider.getIPCLogger().setLevel(Level.SEVERE);
LoggerProvider.getChromiumProcessLogger(). setLevel(Level.SEVERE);
Browser browser = new Browser();
BrowserView view = new BrowserView(browser);
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.add(view, BorderLayout.CENTER);
frame.setSize(700, 500);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
BrowserPreferences preferences = browser.getPreferences();
preferences.setImagesEnabled(false);
int viewWidth = 1280;
int viewHeight = 1000;
// Resize view to the required size
view.setBounds(new Rectangle(viewWidth, viewHeight));
// Wait until web page is loaded completely
invokeAndWaitReady(browser,new jd_yyzz().new ViewThread(browser, url));
JSValue bodyHeight = null;
int firstHeight = 400;
int nowHeight = 400;
while (firstHeight != nowHeight) {
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
firstHeight = nowHeight;
bodyHeight = browser.executeJavaScriptAndReturnValue("document.body.scrollHeight");
//nowHeight = 900;
for (int i = firstHeight; i < nowHeight; i = i + 300) {
browser.executeJavaScriptAndReturnValue("window.scrollTo(0,"+ i + ")");
try {
Thread.sleep(500);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
System.out.println(firstHeight + ":" + nowHeight);
}
viewHeight = nowHeight + 50;
view.setBounds(new Rectangle(viewWidth, viewHeight));
System.out.println("11111------------------:" + viewHeight);
try {
Thread.sleep(1000 * 1);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
bodyHeight = browser.executeJavaScriptAndReturnValue("document.body.scrollHeight");
System.out.println("222222------------------:" + bodyHeight);
int viewHeight_new = ((Number) bodyHeight.getNumber()).intValue() + 50;
if (viewHeight_new > viewHeight) {
System.out.println("33333------------------:" + viewHeight_new);
}
Image image = view.getImage();
BufferedImage bufferedImage = new BufferedImage(100, 50,BufferedImage.TYPE_4BYTE_ABGR);
Graphics2D graphics = (Graphics2D) bufferedImage.getGraphics();
Double scale = 1.0 / view.getDeviceScaleFactor();
graphics.scale(scale, scale);
graphics.drawImage(image,-585, -355, image.getWidth(view), image.getHeight(view),White, null);
try {
String path = "f://shopdetails.jpg";
ImageIO.write(bufferedImage, "JPG", new File(path));
bufferedImage = null;
} catch (IOException e) {
e.printStackTrace();
}
//验证码图片保存之后获取验证码
try {
String result=ImageUtils.readContentFromPost("f://shopdetails.jpg");
browser.executeJavaScriptAndReturnValue("document.getElementById('verifyCode').value = \""+ result + "\";");
Thread.sleep(1000 * 1);
browser.executeJavaScriptAndReturnValue("document.getElementsByClassName('btn')[0].click();");
Thread.sleep(1000 * 1);
return browser.getHTML();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* 线程
* */
class ViewThread extends Thread {
Browser browser;
String openUrl;
public ViewThread(Browser browser, String openUrl) {
this.browser = browser;
this.openUrl = openUrl;
}
public void run() {
browser.loadURL(openUrl);
}
}
/**
* 模拟器加载url
* */
public static void invokeAndWaitReady(Browser browser, Runnable runnable) {
final CountDownLatch latch = new CountDownLatch(1);
LoadAdapter listener = new LoadAdapter() {
@Override
public void onFinishLoadingFrame(FinishLoadingEvent event) {
if (event.isMainFrame()) {
latch.countDown();
}
}
};
browser.addLoadListener(listener);
try {
runnable.run();
try {
if (!latch.await(60, TimeUnit.SECONDS)) {
// throw new RuntimeException(new TimeoutException());
}
} catch (InterruptedException ignore) {
ignore.printStackTrace();
Thread.currentThread().interrupt();
}
} finally {
browser.removeLoadListener(listener);
}
}
}
Java calls the interface provided by the platform for image recognition
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=326217383&siteId=291194637
Ranking