python识图自动化_python selenium 自动化测试图片识别1

本人纯野生测试猿一头,做了一年web 功能测试,测试了一年机顶盒,还是想做回老本行 ,自学了一段时间selenium ,学习过程中,遇到了网页中需要输入验证码的问题,网上查阅资料,依葫芦画瓢凑成(水平有限)了一段登陆网站挂课的脚本(亲测通过),现跟大家分享如下:

大神勿喷

from selenium import webdriver

from selenium.webdriver.common.action_chains import ActionChains

import time

from PIL import Image

from PIL import ImageEnhance

import pytesseract

b = webdriver.Firefox()

b.get("http://www.ouchn.cn/")

time.sleep(5)

ele = b.find_element_by_css_selector\

("html body div#ding div.din div.di2 a.loginbtn")

#print(type(ele))

ele.click()#点击登录

time.sleep(8)

#print(b.window_handles)

b.switch_to_window(b.window_handles[1])

#print(b.current_url)

#b.get(b.current_url)

b.save_screenshot(‘E://aa.png‘) #截取当前网页,该网页有我们需要的验证码

time.sleep(6)

imgelement = b.find_element_by_css_selector("html body form div#box div.box div.kk table tbody tr td label img") #定位验证码

location1 = imgelement.location_once_scrolled_into_view

print(location1)

coderange=(int(location1[‘x‘]),int(location1[‘y‘]+100),int((location1[‘x‘]-30)+130),int((location1[‘y‘]+130))) #写成我们需要截取的位置坐标

i=Image.open(r"E:\aa.png") #打开截图

frame4=i.crop(coderange) #使用Image的crop函数,从截图中再次截取我们需要的区域

frame4.save(r"E:\frame4.png")

i2=Image.open(r"E:\frame4.png")

imgry = i2.convert(‘L‘) #图像加强,二值化,PIL中有九种不同模式。分别为1,L,P,RGB,RGBA,CMYK,YCbCr,I,F。L为灰度图像

sharpness =ImageEnhance.Contrast(imgry)#对比度增强

i3 = sharpness.enhance(3.0) #3.0为图像的饱和度

i3.save("E:\\image_code.png")

i4 = Image.open("E:\\image_code.png")

text = pytesseract.image_to_string(i4).strip() #使用image_to_string识别验证码

print(text)#调试用,查看验证码识别是否成功

b.find_element_by_id("username").clear()

b.find_element_by_id("username").send_keys("此处马赛克")

b.find_element_by_id("password").send_keys("此处马赛克")

b.find_element_by_css_selector("html body form div#box div.box div.kk table tbody tr td label ")

"input#checkCode.biaodan2").send_keys(text)

time.sleep(5)

b.find_element_by_css_selector("html body form div#box div.box div.kk table tbody tr td table tbody tr td label input#btnLogin.anniu").click()

#b.quit()

途中看到网上的大神用location方法就可定位图片元素位置、用size方法可定位长宽大小,但我在使用过程中发现这两个方法都不行,直接报错(我用的python3,可能跟这个有关)。后来偶然发现了location的哥哥location_once_scrolled_into_view,试了一下,沃插,居然能定位出坐标。但size方法还是不行,后来通过审查元素发现也可以发现图片元素的长宽大小。最后试了几下终于能精确截取验证码图片经行识别。

原文地址:http://www.cnblogs.com/huoyunxieshen/p/7891910.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值