Python图像识别参考:http://www.th7.cn/Program/Python/201602/768304.shtml
脚本思路:先获取验证码图片的位置,然后获取元素大小,然后在截取出去验证码图片,然后进行识别就好了
运用到的模块:python图片识别、Python模拟键盘、Selenium鼠标事件
第一步:在C:\Python27\Lib\site-packages\pytesser路径下创建该Python文件,用作图片识别的方法
#coding=utf-8
'''
Created on 2018年4月22日
@author: Administrator
'''
from selenium import webdriver
import time,shutil,random,os
from PIL import Image
from pytesser import *
def identifyImage(driver,element,imageName):
location = element.location
driver.get_screenshot_as_file('screenshot.png')
size = element.size
image = Image.open('screenshot.png')
corped = image.crop((location['x'],location['y'],location['x']+size['width'],location['y']+size['height']))
imagetext = image_to_string(corped).strip()
return imagetext
第二步:实际场景调用图片识别
#coding=utf-8
'''
Created on 2018年4月22日
@author: Administrator
'''
from selenium import webdriver
import time,shutil,random,os
from selenium.webdriver.common.action_chains import ActionChains
import win32api,win32con
from pytesser.IdentifyImage import identifyImage
from PIL import Image
from io import BytesIO
from pytesser import *
def login(username=u'XXXXXX',password=u'XXXXXX'): #登录函数
driver= webdriver.Chrome()
driver.maximize_window()
driver.get('XXXXXX')
driver.implicitly_wait(30)
driver.find_element_by_id('j_username').clear()
driver.find_element_by_id('j_username').send_keys(username)
driver.find_element_by_id('j_password').clear()
driver.find_element_by_id('j_password').send_keys(password)
driver.find_element_by_class_name('bigFont').click()
time.sleep(2)
try:
driver.find_element_by_xpath('//span[contains(text(),"XXXXXX")]').click()
driver.find_element_by_class_name('bigFont').click()
except:
pass
return driver
def editpw(driver): #用例函数
driver.implicitly_wait(20)
time.sleep(3)
driver.find_element_by_class_name('icon-dept').click()
try:
driver.find_element_by_xpath('//div[@id="guide_buttons"]/img[2]').click()
except Exception as e:
print e
elems = driver.find_elements_by_class_name('clientsearch-grid-text')
random.choice(elems).click()
driver.find_element_by_class_name('reSetPassword').click()
time.sleep(2)
elem = driver.find_element_by_class_name('verification-code-img') #定位验证码图片
value = identifyImage(driver,elem,'vCode.jpg') #调用Python图片识别方法
driver.find_element_by_class_name('verification-code-text').send_keys(value) #输入验证码
time.sleep(2)
driver.find_element_by_xpath('//span[contains(text(),"确认")]').click()
try:
message = driver.find_element_by_class_name('crm_prompt_text').text
if message == u'密码已重置,请接收短信和邮件通知!':
return True
return False
except:
return False
driver = login()
Boole = editpw(driver)
print Boole
driver.quit()
PS:登录验证码无需通过该方法处理,可以直接通过添加Cookie来绕过登录验证码,然后该方法只能识别一些简单的图片验证码!