zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    AngularJS Insert Update Delete Using PHP MySQL
    Simple task manager application using AngularJS PHP MySQL
    AngularJS MySQL and Bootstrap Shopping List Tutorial
    Starting out with Node.js and AngularJS
    AngularJS CRUD Example with PHP, MySQL and Material Design
    How to install KVM on Fedora 22
    Fake_AP模式下的Easy-Creds浅析
    河南公务员写古文辞职信
    AI
    政协委员:最大愿望是让小学生步行上学
  • 原文地址:https://www.cnblogs.com/onemorepoint/p/7098159.html
Copyright © 2011-2022 走看看