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

大神勿喷

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方法可定位长宽大小,但我在使用过程中发现这两个方法都不行,直接报错(一年后偶然发现跟驱动有关系)。后来偶然发现了location的哥哥location_once_scrolled_into_view,试了一下,沃插,居然能定位出坐标。但size方法还是不行,后来通过审查元素发现也可以发现图片元素的长宽大小。最后试了几下终于能精确截取验证码图片经行识别。