python截图

WebDriver中实现对特定的Web区域截图方法--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

 

备注: PIL已经停止更新,可以将PIL包名换成pillow

pip install pillow 

 

 

转自 :http://www.myexception.cn/web/2040513.html

posted on 2016-03-23 14:19  kenwong  阅读(1042)  评论(0编辑  收藏  举报

导航