先上代码
需要安装selenium之外,还需要安装以下两个模块
pip install pillow
pip install baidu-aip
from selenium.webdriver.common.by import By
import time
from selenium import webdriver
from PIL import Image
from aip import AipOcr
from os import path
class TestUserLogin:
def __init__(self):
self.driver = webdriver.Chrome()
self.driver.get("http://localhost:8080/jpress/admin/login")
self.driver.maximize_window()
def baiduOCR(self, picfile, outfile): # picfile:图片文件名 outfile:输出文件
# 1.获取验证码 并保存
png = self.driver.find_element(By.ID, "captcha-img")
png.screenshot('capt.png')
# 2.处理下载的图片 灰度处理
img = Image.open('capt.png')
img = img.convert('L') # P模式转换为L模式(灰度模式默认阈值127)
count = 165 # 设定阈值
table = []
for i in range(256):
if i < count:
table.append(0)
else:
table.append(1)
img = img.point(table, '1')
img.save('captcha.png') # 保存处理后的验证码
# 3.识别码 验证码识别 百度云上面的文字识别创建项目里面的参数
filename = path.basename(picfile) # 图片名称
# 百度提供
""" 你的 APPID AK SK """
APP_ID = '你的APP_ID'
API_KEY= '你的API_KEY'
SECRET_KEY = '你的SECRET_KEY'
# 初始化对象
client = AipOcr(APP_ID, API_KEY, SECRET_KEY)
i = open(picfile, 'rb')
img = i.read()
print("正在识别图片:\t" + filename)
""" 调用通用文字识别(高精度版) """
message = client.basicAccurate(img)
print("识别成功!")
i.close()
with open(outfile, 'a+') as fo: # 这边是写进.txt文件
fo.writelines("*" * 60 + '\n') # 搞点花里胡哨的做区分
fo.writelines("识别图片:\t" + filename + "\n" * 2)
fo.writelines("文本内容:\n")
# 输出文本内容
for text in message.get('words_result'): # 识别的内容
fo.writelines(text.get('words') + '\n')
fo.writelines('\n' * 2)
print("文本导出成功!")
time.sleep(1)
self.driver.find_element(By.NAME, "user").send_keys("admin")
self.driver.find_element(By.NAME, "pwd").send_keys("123456")
time.sleep(2)
self.driver.find_element(By.ID, 'captcha').send_keys(text.get('words')) # 找到验证码框并输入验证码
time.sleep(2)
self.driver.find_element(By.LINK_TEXT, ' 登 录').click() # 找到登陆按钮并点击
time.sleep(2)
# 登录之后的页面 断言
urlAfter = self.driver.current_url
if urlAfter == "你的系统登录之后的url":
print("登陆成功")
else:
print("登录失败")
if __name__ == '__main__':
outfile = "export1.txt"
TestUserLogin().baiduOCR('captcha.png', outfile)
说明:
参考文章:https://www.jb51.net/article/174684.htm
百度云:https://cloud.baidu.com/product/ocr_general
需要注册百度云账号 搜索文字识别功能获取APP-ID等,注册创建好项目之后要免费领取次数,否则会报错
这个识别图片有时候会不准确,简单的图片验证码没有那么多干扰的时候可以成功、