PythonUI 识别登录页面验证码(PIL)
from time import sleep import PIL import pytesseract from PIL import Image, ImageEnhance from selenium import webdriver # 1、打开浏览器,最大化浏览器 driver = webdriver.Firefox() driver.get("http://172.31.21.148:30111/#/login") driver.implicitly_wait(10) driver.maximize_window() # 用户名元素/密码元素 userElement = driver.find_element_by_xpath("/html/body/div/div/div/div[1]/div/form/div[1]/div/div[1]/input") passElement = driver.find_element_by_xpath("/html/body/div/div/div/div[1]/div/form/div[2]/div/div/input") userElement.send_keys('admin') passElement.send_keys('admin1') # 保存验证码并读取 driver.save_screenshot('E://01.png') imgelement = driver.find_element_by_xpath("/html/body/div/div/div/div[1]/div/form/div[3]/div/div[3]/div/div/img") # 定位验证码 location = imgelement.location # 获取验证码x,y轴坐标 print(location['x'],location['y']) size = imgelement.size # 获取验证码的长宽 print(size['height'],size['width']) rangle = (1360,420,1600,490) # 写成我们需要截取的位置坐标 #rangle = (int(location['x'])+500, int(location['y']), int(location['x'] + size['width']), #int(location['y'] + size['height'])) # 写成我们需要截取的位置坐标 i = Image.open("E://01.png") # 打开截图 imgCaptcha = i.crop(rangle) # 使用Image的crop函数,从截图中再次截取我们需要的区域 imgCaptcha.save('E://02.png')#截取到的验证码保存为png图片 qq=Image.open('E://02.png')#打开png验证码图片 imgry = qq.convert('L') # 图像加强,二值化 sharpness = ImageEnhance.Contrast(imgry) # 对比度增强 sharp_img = sharpness.enhance(3.0) sharp_img.save("E://03.png") yzm=Image.open('E://03.png') text=pytesseract.image_to_string(yzm).strip() #使用image_to_string识别验证码 print(text) sleep(3) driver.find_element_by_xpath("/html/body/div/div/div/div[1]/div/form/div[3]/div/div[1]/div/div/div/input").send_keys(text)#将识别的图片验证码信息输入到验证码输入文本框中 sleep(3) click_login = driver.find_element_by_xpath("/html/body/div/div/div/div[1]/div/form/div[4]/div/div/img") click_login.click() sleep(5) driver.quit()