zoukankan      html  css  js  c++  java
  • python+selenium2自动化---使用pytesseract和Pillow实现验证码识别

    这种方式只能对简单的验证码起作用,复杂的就获取不到了。

    验证码识别思路:

    1、获取整个屏幕截图

    2、获取验证码图片的坐标

    3、抠图获取验证码图片

    4、使用pytesseract识别验证码

    示例代码

    import os
    from time import sleep
    
    import pytesseract
    from selenium import webdriver
    from PIL import Image
    
    class TestCase():
        def __init__(self):
            self.driver = webdriver.Chrome()
            self.driver.maximize_window()
            self.driver.get('http://es.bnuz.edu.cn/')
    
        def test01(self):
            #获取屏幕截图
            self.driver.get_screenshot_as_file(os.path.dirname(__file__)+'/屏幕截图.png')
            #获取验证码图片元素
            ele = self.driver.find_element_by_xpath('//*[@id="yzm_dd"]/img')
            #获取验证码图片左上角的坐标
            location = ele.location
            size = ele.size
            print(location)
            print(size)
            #验证码图片的大小
            left = location['x']
            top = location['y']
            right = size['width'] + left
            height = size['height'] + top
    
            #如果是retina屏幕,需要这样
            dpr = self.driver.execute_script('return window.devicePixelRatio')
    
            #抠图获取验证码图片
            im = Image.open(os.path.dirname(__file__)+'/屏幕截图.png')
            im_new = im.crop((left*dpr,top*dpr,right*dpr,height*dpr))
            im_new.save(os.path.dirname(__file__)+'/验证码图片.png')
    
            sleep(3)
            self.driver.quit()
    
        def test02():
            img = Image.open(os.path.dirname(__file__)+'/验证码图片.png')
            res = pytesseract.image_to_string(img)
            print(res)
    
    
    if __name__ == '__main__':
        TestCase.test02()

    获取到的整个屏幕截图:

    验证码图片:

    输出结果:

  • 相关阅读:
    合理的嵌入式开发学习路线
    Nginx
    RARP
    强弱电共地
    ACDC
    各电脑进Bios方法
    Java中Integer.parseInt
    全排列
    Java实现LRU缓存方案?
    缓存有关的几个问题
  • 原文地址:https://www.cnblogs.com/Xiaojiangzi/p/13462050.html
Copyright © 2011-2022 走看看