• WebDriver中自动识别验证码--Python实现


     

    一、在自动化测试中,遇到验证码的处理方法有以下两种:

    1、找开发去掉验证码或者使用万能验证码

    2、使用OCR自动识别

    这里,方法一只要和研发沟通就行。

    使用pytesseract自动化识别,一般识别率不是太高,处理一般简单验证码还是没问题,例如下面这种验证码:

    使用非常简单,只需下面几步:

    import pytesseract
    from PIL import Image
    image=Image.open('new.jpg')
    vcode=pytesseract.image_to_string(image)
    print vcode

    二、但在使用python自动化测试中会遇到一个难点,验证码怎么获取,python的webdriver API没有这样接口。baidu查之,网上只有java的解决方案,python的貌似没有,在这就将python的解决方案写下,以供需要的人参考:

      解决方法:

      从页面获取验证码的坐标值得,使用PIL的Image模块,截取特定的区域,代码如下:

    思路:将web节目截图保存-->定位到验证码坐标-->从截图中再进行验证码位置的截图

    复制代码
    from PIL import Image
    import pytesseract
    from selenium import webdriver
    
    url='http://xxxxx.com'
    driver = webdriver.Chrome()
    driver.maximize_window()  #将浏览器最大化
    driver.get(url)
    driver.save_screenshot('f://aa.png')  #截取当前网页,该网页有我们需要的验证码
    imgelement = driver.find_element_by_xpath('//img[@src="rand!loginRand.action"]')  #定位验证码
    location = imgelement.location  #获取验证码x,y轴坐标
    size=imgelement.size  #获取验证码的长宽
    rangle=(int(location['x']),int(location['y']),int(location['x']+size['width']),int(location['y']+size['height'])) #写成我们需要截取的位置坐标
    i=Image.open("f://aa.png") #打开截图
    frame4=i.crop(rangle)  #使用Image的crop函数,从截图中再次截取我们需要的区域
    frame4.save('f://frame4.jpg')
    qq=Image.open('f://frame4.jpg')
    text=pytesseract.image_to_string(qq).strip() #使用image_to_string识别验证码
    print text
    复制代码

    参考模块:

    Image模块:http://effbot.org/imagingbook/image.htm#tag-Image.Image.crop

    pytesseract识别验证码方法:http://www.waitalone.cn/python-php-ocr.html

     原文链接:http://www.cnblogs.com/landhu/p/4968577.html

  • 相关阅读:
    Linux scp、ssh命令
    Linux ps、top、free、uname命令
    适配器模式
    Linux不能进入图形化界面运行yum不管用
    SpringMVC 测试 mockMVC
    Idea和Git集成,并且Git管理不同的秘钥,idea分别提交项目到GitLab和GitHub
    多线程
    Java中Volatile关键字详解
    Spring事务管理--(二)嵌套事物详解
    jConsole, jVisualvm, btrace 区别和联系
  • 原文地址:https://www.cnblogs.com/onemorepoint/p/7098159.html
Copyright © 2020-2023  润新知