Selenium+Tesseract-OCR智能识别验证码爬取网页数据的实例

时间:2021-08-24 08:43:25

1.项目需求描述

通过订单号获取某系统内订单的详细数据,不需要账号密码的登录验证,但有图片验证码的动态识别,将获取到的数据存到数据库。

2.整体思路

  1.通过Selenium技术,无窗口模式打开浏览器

  2.在输入框中动态输入订单号

  3.将图片验证码截图保存到本地

  4.通过Tesseract-OCR技术去本地识别验证码转化为文字

  5.将获取的验证码输入输入框

  6.点击查询获取列表数据

3.功能实现

1.下载并安装Google浏览器,安装Google驱动chromedriver.exe,获取安装路径,配置在项目中

2.使用Selenium进行浏览器操作

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
System.setProperty(浏览器驱动, 浏览器驱动安装位置);
ChromeOptions options = new ChromeOptions();
options.addArguments("--headless");                            // 无窗口模式
options.addArguments("--disable-infobars");                    // 禁言消息条
options.addArguments("--disable-extensions");                  // 禁用插件
options.addArguments("--disable-gpu");                         // 禁用GPU
options.addArguments("--no-sandbox");                          // 禁用沙盒模式
options.addArguments("--disable-dev-shm-usage");
options.addArguments("--hide-scrollbars");                     // 隐藏滚动条
 
WebDriver driver = new ChromeDriver(options);
driver.get(爬取网站URL);
driver.manage().window().setSize(new Dimension(450, 260));     // 设置游览器打开后调整大小
try {
    // 保存IMG图片到本地
    saveImgToLocal(driver);
    Thread.sleep(2000);
    // OCR智能识别验证码
    String codeByOCR = getCodeByOCR();
    if (codeByOCR != null) {
        try {
            WebElement input1 = driver.findElement(By.id(TEXTBOX1));
            input1.sendKeys(code);
            WebElement input2 = driver.findElement(By.id(TEXTBOX2));
            input2.sendKeys(codeByOCR);
            // 获取table数据
            WebElement addButton = driver.findElement(By.id(SELECT_BUTTON));
            addButton.click();
            List<WebElement> tRCollection = driver.findElement(By.id(TABLE_ID)).findElements(By.tagName("tr"));
            for (int t = 1; t < tRCollection.size(); t++) {
                List<WebElement> tDCollection = tRCollection.get(t).findElements(By.tagName("td"));
                VipLogisticsMinHangDetailVo minHangDetailVo = new VipLogisticsMinHangDetailVo();
                minHangDetailVo.setLogistics_number(code);
                for (int i = 0; i < tDCollection.size(); i++) {
                    String text = tDCollection.get(i).getText();
                    switch (i) {
                        case 0:
                            minHangDetailVo.setTime(text);
                        case 1:
                            minHangDetailVo.setOutlet(text);
                        case 2:
                            minHangDetailVo.setOrganization(text);
                        case 3:
                            minHangDetailVo.setEvent(text);
                        case 4:
                            minHangDetailVo.setDetail(text);
                    }
                }
                list.add(minHangDetailVo);
            }
            log.info("验证码识别成功!");
        } catch (Exception e) {
            if (e.toString().contains("错误提示:验证码错误或已过期!")) {
                log.error("验证码识别错误!" + e.toString());
            } else if (e.toString().contains("错误提示:请输入验证码!")) {
                log.error("未输入验证码!:" + e.toString());
            } else {
                log.error("其他异常:" + e.toString());
            }
        }
    }
    driver.quit();
} catch (Exception e) {
    e.printStackTrace();
}

3.将图片验证码截图保存到本地(截屏法)

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
private void saveImgToLocal(WebDriver driver) {
    WebElement element = driver.findElement(By.id(img元素ID));
    //创建全屏截图
    WrapsDriver wrapsDriver = (WrapsDriver) element;
    File screen = ((TakesScreenshot) wrapsDriver.getWrappedDriver()).getScreenshotAs(OutputType.FILE);
    try {
        BufferedImage image = ImageIO.read(screen);
        //创建一个矩形使用上面的高度,和宽度
        Point p = element.getLocation();
        //元素坐标
        BufferedImage img = image.getSubimage(p.getX(), p.getY(), element.getSize().getWidth(), element.getSize().getHeight());
        ImageIO.write(img, "png", screen);
 
        FileUtils.copyFile(screen, new File(保存本地地址 + "imgname.png"));
    } catch (IOException e) {
        e.printStackTrace();
    }
}

4.将图片验证码保存到本地(鼠标法)

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
private static void saveImgToLocal1(WebDriver driver) {
    Actions action = new Actions(driver);
    action.contextClick(driver.findElement(By.id(img元素ID))).build().perform();
    try {
        Robot robot = new Robot();
        Thread.sleep(1000);
 
        robot.keyPress(KeyEvent.VK_DOWN);
        Thread.sleep(1000);
 
        robot.keyPress(KeyEvent.VK_DOWN);
        Thread.sleep(1000);
 
        robot.keyPress(KeyEvent.VK_ENTER);
        Thread.sleep(1000);
        //释放向下键,不然在此之前的条目将起作用
        robot.keyRelease(KeyEvent.VK_DOWN);
        Thread.sleep(1000);
        //运行保存
        Runtime.getRuntime().exec(SAVE_IMG_EXE);
        Thread.sleep(10000);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

5.对本地验证码进行OCR识别

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
private String getCodeByOCR() {
    String result = null;
    File file = new File(本地图片地址);
    if (!file.exists()) {
        if (systemFalg != 1) {
            file.setWritable(true, false);
        }
        file.mkdirs();
    }
    File imageFile = new File(本地图片地址 + "imgname.png");
    if (imageFile.exists()) {
        ITesseract instance = new Tesseract();
        instance.setDatapath(tessdata存放地址);
        try {
            String doOCR = instance.doOCR(imageFile);
            result = replaceBlank(doOCR);
            log.info("解析的验证码为:{}", result != null ? result : "为空!");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("解析验证码异常!");
        }
    } else {
        log.error("解析验证码的文件不存在!");
    }
    return result;
}

综上,该网页的数据就可以获取了。

到此这篇关于Selenium+Tesseract-OCR智能识别验证码爬取网页数据的实例的文章就介绍到这了,更多相关Selenium+Tesseract-OCR智能识别验证码爬取 内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://www.cnblogs.com/zhaohadoopone/p/15338813.html