前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python 识别登录验证码图片功能的实现代码(完整代码)

python 识别登录验证码图片功能的实现代码(完整代码)

作者头像
砸漏
发布2020-10-21 11:59:30
1.9K0
发布2020-10-21 11:59:30
举报
文章被收录于专栏:恩蓝脚本恩蓝脚本

在编写自动化测试用例的时候,每次登录都需要输入验证码,后来想把让python自己识别图片里的验证码,不需要自己手动登陆,所以查了一下识别功能怎么实现,做一下笔记。

首选导入一些用到的库,re、Image、pytesseract、selenium、time

代码语言:javascript
复制
import re # 用于正则
from PIL import Image # 用于打开图片和对图片处理
import pytesseract # 用于图片转文字
from selenium import webdriver # 用于打开网站
import time # 代码运行停顿

首先需要获取验证码图片,才能进一步识别。

创建类,定义webdriver和find_element_by_selector方法,用来打开网页和定位验证码图片的元素

代码语言:javascript
复制
class VerificationCode:
  def __init__(self):
    self.driver = webdriver.Firefox()
    self.find_element = self.driver.find_element_by_css_selector

然后打开浏览器截取验证码图片

代码语言:javascript
复制
 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阈值,超过阈值的为黑色

代码语言:javascript
复制
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

经过灰度处理后的图片

然后删除一些扰乱识别的像素点。

代码语言:javascript
复制
  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的路径,因为默认路径是错的,然后转换图片为文字,由于个别图片中识别会出现处理遗漏,会被识别成空格或则点或则分号什么的,所以增加了一个去除验证码中特殊字符的处理。

PS:tesseract文件下载链接

代码语言:javascript
复制
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

完整代码如下:

代码语言:javascript
复制
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()

看评论有很多人需要tesseract.exe文件,但是由于文件过大,发邮件会出现无法下载的情况,有需要的可以在一下连接里下载tesseract.exe文件

到此这篇关于python 识别登录验证码图片(完整代码)的文章就介绍到这了,更多相关python识别登录验证码图片内容请搜索ZaLou.Cn以前的文章或继续浏览下面的相关文章希望大家以后多多支持ZaLou.Cn!

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-09-11 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
验证码
腾讯云新一代行为验证码(Captcha),基于十道安全栅栏, 为网页、App、小程序开发者打造立体、全面的人机验证。最大程度保护注册登录、活动秒杀、点赞发帖、数据保护等各大场景下业务安全的同时,提供更精细化的用户体验。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档