python识别验证码图片实例详解
作者:沉默的鹏先生 发布时间:2022-02-13 10:23:53
标签:python,识别验证码
在编写自动化测试用例的时候,每次登录都需要输入验证码,后来想把让python自己识别图片里的验证码,不需要自己手动登陆,所以查了一下识别功能怎么实现,做一下笔记。
首选导入一些用到的库,re、Image、pytesseract、selenium、time
import re # 用于正则
from PIL import Image # 用于打开图片和对图片处理
import pytesseract # 用于图片转文字
from selenium import webdriver # 用于打开网站
import time # 代码运行停顿
首先需要获取验证码图片,才能进一步识别。
创建类,定义webdriver和find_element_by_selector方法,用来打开网页和定位验证码图片的元素
class VerificationCode:
def __init__(self):
self.driver = webdriver.Firefox()
self.find_element = self.driver.find_element_by_css_selector
然后打开浏览器截取验证码图片
def get_pictures(self):
self.driver.get('http://123.255.123.3') # 打开登陆页面
self.driver.save_screenshot('pictures.png') # 全屏截图
page_snap_obj = Image.open('pictures.png')
img = self.find_element('#pic') # 验证码元素位置
time.sleep(1)
location = img.location
size = img.size # 获取验证码的大小参数
left = location['x']
top = location['y']
right = left + size['width']
bottom = top + size['height']
image_obj = page_snap_obj.crop((left, top, right, bottom)) # 按照验证码的长宽,切割验证码
image_obj.show() # 打开切割后的完整验证码
self.driver.close() # 处理完验证码后关闭浏览器
return image_obj
未处理前的验证码图片如下:
未处理的验证码图片,对于python来说识别率较低,仔细看可以发现图片里有很对五颜六色扰乱识别的点,非常影响识别率。
下面对获取的验证码进行处理。
首先用convert把图片转成黑白色。设置threshold阈值,超过阈值的为黑色
def processing_image(self):
image_obj = self.get_pictures() # 获取验证码
img = image_obj.convert("L") # 转灰度
pixdata = img.load()
w, h = img.size
threshold = 160 # 该阈值不适合所有验证码,具体阈值请根据验证码情况设置
# 遍历所有像素,大于阈值的为黑色
for y in range(h):
for x in range(w):
if pixdata[x, y] < threshold:
pixdata[x, y] = 0
else:
pixdata[x, y] = 255
return img
经过灰度处理后的图片
然后删除一些扰乱识别的像素点。
def delete_spot(self):
images = self.processing_image()
data = images.getdata()
w, h = images.size
black_point = 0
for x in range(1, w - 1):
for y in range(1, h - 1):
mid_pixel = data[w * y + x] # 中央像素点像素值
if mid_pixel < 50: # 找出上下左右四个方向像素点像素值
top_pixel = data[w * (y - 1) + x]
left_pixel = data[w * y + (x - 1)]
down_pixel = data[w * (y + 1) + x]
right_pixel = data[w * y + (x + 1)]
# 判断上下左右的黑色像素点总个数
if top_pixel < 10:
black_point += 1
if left_pixel < 10:
black_point += 1
if down_pixel < 10:
black_point += 1
if right_pixel < 10:
black_point += 1
if black_point < 1:
images.putpixel((x, y), 255)
black_point = 0
# images.show()
return images
经过去除噪点处理后的图片
最后把处理后的图片转成文字。
先设置pytesseract的路径,因为默认路径是错的,然后转换图片为文字,由于个别图片中识别会出现处理遗漏,会被识别成空格或则点或则分号什么的,所以增加了一个去除验证码 * 殊字符的处理。
def image_str(self):
image = self.delete_spot()
pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe" # 设置pyteseract路径
result = pytesseract.image_to_string(image) # 图片转文字
resultj = re.sub(u"([^\u4e00-\u9fa5\u0030-\u0039\u0041-\u005a\u0061-\u007a])", "", result) # 去除识别出来的特殊字符
result_four = resultj[0:4] # 只获取前4个字符
# print(resultj) # 打印识别的验证码
return result_four
完整代码如下:
import re # 用于正则
from PIL import Image # 用于打开图片和对图片处理
import pytesseract # 用于图片转文字
from selenium import webdriver # 用于打开网站
import time # 代码运行停顿
class VerificationCode:
def __init__(self):
self.driver = webdriver.Firefox()
self.find_element = self.driver.find_element_by_css_selector
def get_pictures(self):
self.driver.get('http://123.255.123.3') # 打开登陆页面
self.driver.save_screenshot('pictures.png') # 全屏截图
page_snap_obj = Image.open('pictures.png')
img = self.find_element('#pic') # 验证码元素位置
time.sleep(1)
location = img.location
size = img.size # 获取验证码的大小参数
left = location['x']
top = location['y']
right = left + size['width']
bottom = top + size['height']
image_obj = page_snap_obj.crop((left, top, right, bottom)) # 按照验证码的长宽,切割验证码
image_obj.show() # 打开切割后的完整验证码
self.driver.close() # 处理完验证码后关闭浏览器
return image_obj
def processing_image(self):
image_obj = self.get_pictures() # 获取验证码
img = image_obj.convert("L") # 转灰度
pixdata = img.load()
w, h = img.size
threshold = 160
# 遍历所有像素,大于阈值的为黑色
for y in range(h):
for x in range(w):
if pixdata[x, y] < threshold:
pixdata[x, y] = 0
else:
pixdata[x, y] = 255
return img
def delete_spot(self):
images = self.processing_image()
data = images.getdata()
w, h = images.size
black_point = 0
for x in range(1, w - 1):
for y in range(1, h - 1):
mid_pixel = data[w * y + x] # 中央像素点像素值
if mid_pixel < 50: # 找出上下左右四个方向像素点像素值
top_pixel = data[w * (y - 1) + x]
left_pixel = data[w * y + (x - 1)]
down_pixel = data[w * (y + 1) + x]
right_pixel = data[w * y + (x + 1)]
# 判断上下左右的黑色像素点总个数
if top_pixel < 10:
black_point += 1
if left_pixel < 10:
black_point += 1
if down_pixel < 10:
black_point += 1
if right_pixel < 10:
black_point += 1
if black_point < 1:
images.putpixel((x, y), 255)
black_point = 0
# images.show()
return images
def image_str(self):
image = self.delete_spot()
pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe" # 设置pyteseract路径
result = pytesseract.image_to_string(image) # 图片转文字
resultj = re.sub(u"([^\u4e00-\u9fa5\u0030-\u0039\u0041-\u005a\u0061-\u007a])", "", result) # 去除识别出来的特殊字符
result_four = resultj[0:4] # 只获取前4个字符
# print(resultj) # 打印识别的验证码
return result_four
if __name__ == '__main__':
a = VerificationCode()
a.image_str()
来源:https://blog.csdn.net/ever_peng/article/details/90547299


猜你喜欢
- 本文实例讲述了Python使用matplotlib绘制正弦和余弦曲线的方法。分享给大家供大家参考,具体如下:一 介绍关键词:绘图库官网:ht
- 最近做了一个项目,将从微信下载的音频文件(默认为.amr格式)转化为mp3格式(否则前端播放将会遇到困难)上传到云端。经过一番研究,最终决定
- JSON(Javascript Object Notation)是一种轻量级的数据交换语言,以文字为基础,具有自我描述性且易于让人阅读。尽管
- 模块概述如果说模块是按照逻辑来组织 Python 代码的方法, 那么文件便是物理层上组织模块的方法。 因此, **一个文件被看作是一个独立模
- 本文实例讲述了Python2.7+pytesser实现简单验证码的识别方法。分享给大家供大家参考,具体如下:首先,安装Python2.7版本
- 在使用Celery统计每日访问数量的时候,发现一个任务会同时执行两次,发现同一时间内(1s内)竟然同时发送了两次任务,也就是同时产生了两个w
- 1.3 安装 ASP.net跟基督山一起检查你们的计算机哦CPU Pentium II 450以上,推荐733内存 256M 推荐 512M
- 我们知道 Django Auth 应用一般用在用户的登录注册上,用于判断当前的用户是否合法,从而可以帮助开发者快速的构建用户系统,那么 Au
- 概要:本文主要描述XHTML中相对定位和绝对定位各自的本质、用法、区别和两者之间的关系。以及使用CSS的Left、Right、Top、Bot
- 一、准备工作:1、安装mysql3.7,创建一个test数据库,创建student表,创建列:(列名看代码),创建几条数据(以上工作直接用n
- 本文实例讲述了wxPython主框架的简单用法,分享给大家供大家参考。具体如下:程序代码如下:import wx class MyApp(w
- 原文链接:https://blog.csdn.net/Fairy_Nan/article/details/105914203HDF也是一种自
- 前言业务需求中需要连接两个数据库处理数据,需要用动态数据源。通过了解mybatis的框架,计划 使用分包的方式进行数据源的区分。原理前提:我
- 实现目标:mysql下将自增主键的值,从10000开始,即实现自增主键的种子为10000。方案1)使用alter table `tablen
- 代码如下:< % '功能:显示数据库中表名、字段名、字段内容 '原创:wangsdong
- 错误代码如下:NotFoundError (see above for traceback): Unsuccessful TensorSli
- 看代码: HTML: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transi
- js实现千分符转化function fmoney(s, n){ n = n > 0 && n <= 20 ? n
- 如果要在某个数组中删除一个元素,可以直接用的unset,但今天看到的东西却让我大吃一惊<?php$arr = array('a
- 这篇文章主要介绍了Python魔法方法 容器部方法详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋