在编写自动化测试用例的时候,每次登录都需要输入验证码,后来想把让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. Parsing error: missing-whitespace-between-attributes

    给如下位置添加空格即可 在文件末尾添加一空白行即可

  2. 你到底懂不懂JavaScript?来做做这12道面试题试试!

    携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第 21 天,点击查看活动详情 JavaScript 是每一个前端开发者都应该掌握的基础技术,但是很多时候,你可能并不完全懂 Jav ...

  3. function的length,就是第一个具有默认值之前的参数个数。

    一个拥有 length 属性和若干索引属性的对象就可以被称为类数组对象,类数组对象和数组类似,但是不能调用数组的方法.常见的类数组对象有 arguments 和 DOM 方法的返回结果,还有一个函数也 ...

  4. finalshell如何查看密码

    1.右键点击导出 2.打开导出的配置文件,搜索password,找到password的编码后的字符串复制 3.运行下面代码,即可查看原来的密码,把main()方法的字符串替换成上一步复制的字符串imp ...

  5. Lnmp切换PHP版本

    进入lnmp的安装目录 cd /root/lnmp1.8 执行 ./install.sh mphp 然后选择你要变更的版本

  6. pip安装psycopg2报错Could not find a version that satisfies the requirement psycopg2

    pip安装psycopg2报错 在使用命令(pip install psycopg2)安装psycopg2时,会报错: ERROR: Could not find a version that sat ...

  7. leecode76. 最小覆盖子串

    76. 最小覆盖子串 给你一个字符串 s .一个字符串 t .返回 s 中涵盖 t 所有字符的最小子串.如果 s 中不存在涵盖 t 所有字符的子串,则返回空字符串 "" . 注意: ...

  8. PyCharm如何实现控制台换行显示

    举个例子 我现在想要看输出结果的所有数据然后再控制台输出的信息如下: 本来输出的内容有很多,但由于只显示了一行,因此想要看全部的内容还需要拖拉滚动条,挺麻烦的,而且看着也不方便,怎么让控制台信息全都直 ...

  9. php functions 生成唯一码

    <?php /** * 微擎密码生成 * */ function we7password($passwordinput, $salt, $authkey) { $passwordinput = ...

  10. zabbix编译安装,安装mysql数据库:configure: error: Not found mysqlclient library

    在编译时,可能会出现题目中所示的错误,可以通过安装mysql-devel这个库解决: # yum install mysql-devel 注:如果出现"configure: error : ...