在编写自动化测试用例的时候,每次登录都需要输入验证码,后来想把让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的路径,因为默认路径是错的,然后转换图片为文字,由于个别图片中识别会出现处理遗漏,会被识别成空格或则点或则分号什么的,所以增加了一个去除验证码中特殊字符的处理。 PS:tesseract文件下载链接 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()
看评论有很多人需要tesseract.exe文件,但是由于文件过大,发邮件会出现无法下载的情况,有需要的可以在一下连接里下载tesseract.exe文件 下载地址:https://download.csdn.net/download/ever_peng/11938731

python 识别登陆验证码图片(完整代码)的更多相关文章

  1. Python识别网站验证码

    http://drops.wooyun.org/tips/6313 Python识别网站验证码 Manning · 2015/05/28 10:57 0x00 识别涉及技术 验证码识别涉及很多方面的内 ...

  2. 基于Python使用SVM识别简单的字符验证码的完整代码开源分享

    关键字:Python,SVM,字符验证码,机器学习,验证码识别 1   概述 基于Python使用SVM识别简单的验证字符串的完整代码开源分享. 因为目前有了更厉害的新技术来解决这类问题了,但是本文作 ...

  3. Python识别字符型图片验证码

    前言 验证码是目前互联网上非常常见也是非常重要的一个事物,充当着很多系统的 防火墙 功能,但是随时OCR技术的发展,验证码暴露出来的安全问题也越来越严峻.本文介绍了一套字符验证码识别的完整流程,对于验 ...

  4. mac使用python识别图形验证码

    前言 最近在研究验证码相关的操作,所以准备记录下安装以及使用的过程.虽然之前对验证码的破解有所了解的,但是之前都是简单使用之后就不用了,没有记录一个详细的过程,所以后面再用起来也要重新从网上查找资料比 ...

  5. ppt和pptx转图片完整代码,解决2003版和2007版中文乱码问题

    引入所需依赖,注意poi版本,新版本不支持,最好使用和我一样的版本. <!-- https://mvnrepository.com/artifact/org.apache.poi/poi --& ...

  6. python爬取许多图片的代码

    from bs4 import BeautifulSoup import requests import os os.makedirs('./img/', exist_ok=True) URL = & ...

  7. 纯代码系列:Python实现验证码图片(PIL库经典用法用法,爬虫12306思路)

    现在的网页中,为了防止机器人提交表单,图片验证码是很常见的应对手段之一.这里就不详细介绍了,相信大家都遇到过. 现在就给出用Python的PIL库实现验证码图片的代码.代码中有详细注释. #!/usr ...

  8. 【转】DelphiXE10.2.3——跨平台生成验证码图片

    原文地址 Java.PHP.C#等很容易在网上找到生成验证码图片的代码,Delphi却寥寥无几,昨天花了一整天时间,做了个跨平台的验证码,可以用在C/S和B/S端,支持Windows.Linux.An ...

  9. 文字识别还能这样用?通过Python做文字识别到破解图片验证码

    前期准备 1. 安装包,直接在终端上输入pip指令即可: # 发送浏览器请求 pip3 install requests # 文字识别 pip3 install pytesseract # 图片处理 ...

  10. python爬虫20 | 小帅b教你如何使用python识别图片验证码

    当你在爬取某些网站的时候 对于你的一些频繁请求 对方会阻碍你 常见的方式就是使用验证码 验证码的主要功能 就是区分你是人还是鬼(机器人) 人 想法设法的搞一些手段来对付技术 而 技术又能对付人们的想法 ...

随机推荐

  1. 使用python往已有内容的PDF文件写入数据

    只使用reportlab库好像没法在已经有内容的PDF页面中写入数据,只能生成一个空的PDF文件再写入.所以这里我是配合pdfrw库来实现的.具体见示例 from reportlab.pdfgen.c ...

  2. vue学习 第二天 CSS基础

    CSS: 层叠样式表  ( Cascading Style Sheets ) 的简称 1.css简介 1)也是一种标记语言 2)主要用来设置html页面中,标签的样式. 3)css美化了html页面, ...

  3. Kubernetes 安装网络插件(calico)

    简介 Calico是Kubernetes生态系统中另一种流行的网络选择.虽然Flannel被公认为是最简单的选择,但Calico以其性能.灵活性而闻名.Calico的功能更为全面,不仅提供主机和pod ...

  4. 推荐ssh工具

    介绍一些我常用的ssh工具 1.Xshell ​ Xshell应该是一款家喻户晓的ssh连接工具,本人有幸也在很长一段时间都在使用Xshell,但是Xshell他是收费的!而且每次关闭后都会有一个提示 ...

  5. 关于MYSQL知识点复习

    关于MYSQL关联查询JOIN:   https://www.cnblogs.com/withscorpion/p/9454490.html

  6. Git相关、Gitee多人协同开发

    Git相关 1.介绍 ​ 是一个具有版本控制的软件,控制开发的项目代码,具有集群化.多分支的功能 2.对于程序员的作用 协同开发 解决代码合并过程中冲突 代码版本管理 3.git 与 svn 比较 ​ ...

  7. open-local部署和使用

    Open-Local简介 Open-local 是阿里巴巴开源,由多个组件构成的本地磁盘管理系统,目标是解决当前kubernetes本地存储能力缺失问题. Open-Local包含四大类组件: • S ...

  8. vba_pj_0001_auto_date

    Const init_info As String = "InitInfo"Const end_row_op As Integer = 100  'tmpConst end_row ...

  9. fastjson场景

    json转java对象 // 将Json字符串通过fastjson转为JSONObject对象 JSONObject jsonObject = JSONObject.parseObject(userJ ...

  10. nanoPi R1 资料

    eflasher脱机烧写 在命令行终端中通过执行下列命令进行烧写: $ su root $ eflasher root 用户的密码是 fa.   串口登录 控制台波特率 115200