截取验证码图片及规则验证码的读取

对于Web应用来说,大部分的系统在用户登录时都要求用户输入验证码。对于测试人员来说,不管是进行性能测试还是自动化测试,都是一个比较棘手的问题。
常见的验证码处理方法有如下几种:
1.去掉验证码
2.设置万能验证码
3.验证码识别技术
4.记录Cookie
下面着重讲述验证码识别技术
在 Python中可以通过Python-tesseract来识别图片中的验证码。Python-tesseract是光学字符识别Tesseract OCR引擎的Python封装类,能够读取任何常规的图片文件(JPG、GIF、PNG、TIFF)等
截取验证码图片
# coding=utf-8
from selenium import webdriver
from time import sleep
# 需要在命令行模式下输入pip install pillow安装
from PIL import Image
# 调用浏览器驱动,驱动浏览器
driver = webdriver.Chrome()
# 打开页面
driver.get("http://49.4.68.71/ntsp-cc-portal/#/")
# 最大化窗口
driver.maximize_window()
sleep(5)
# 截取网页图片
driver.save_screenshot("d:/test.png")
# 通过xpath方法获取元素
code_element = driver.find_element_by_xpath("//*[@id='block']/div/img")
# 通过location方法获取元素位置(结果为{"x":123,"y":345})
print(code_element.location)
# 当用location方法定位元素坐标存在偏差时,可在对应该坐标中加相应数值(如果无偏差则不加)
left = code_element.location["x"] + 140
print(type(left))
top = code_element.location["y"] + 100
# 获取元素的长度与高度
# size = code_element.size # 获取验证码的长宽
right = code_element.size["width"] + left + 30
print(right)
height = code_element.size["height"] + top + 20
print(height)
# 打开图片当成一个对象
im = Image.open("d:/test.png")
# crop()按照一定坐标裁剪图片,提取验证码图片
img = im.crop((left, top, right, height))
# 将提取的图片进行保存
img.save("d:/test1.png")
pytesseract读取规则验证码
# coding:utf-8
import pytesseract
from PIL import Image
image = Image.open("d:/test1.png")
text = pytesseract.image_to_string(image)
print(text)
此种方法只能读取图片中只有数字的验证,无法读取图片中存在符号、线条之类或有干扰项的验证码