python自动化操作之动态验证码、滑动验证码的降噪和识别


Posted in Python onAugust 30, 2021

前言

python对动态验证码、滑动验证码的降噪和识别,在各种自动化操作中,我们经常要遇到沿跳过验证码的操作,而对于验证码的降噪和识别,的确困然了很多的人。这里我们就详细讲解一下不同验证码的降噪和识别。

一、动态验证码 

  • 动态验证码是服务端生成的,点击一次,就会更换一次,这就会造成很多人在识别的时候,会发现验证码一直过期
  • 这是因为,如果你是把图片下载下来,进行识别的话,其实在下载的这个请求中,其实相当于点击了一次,这个验证码的内容已经被更换了
  • 最好的方法是,打开这个页面后,将页面进行截图,然后定位到验证码的位置,将验证码从截图上面裁剪下来进行识别,这样就不会造成多次请求,验证码更换的情况了

python自动化操作之动态验证码、滑动验证码的降噪和识别

from selenium import webdriver
from PIL import Image
 
# 实例化浏览器
driver = webdriver.Chrome()
 
# 最大化窗口
driver.maximize_window()
 
# 打开登陆页面
driver.get(# 你的url地址)
 
# 保存页面截图
driver.get_screenshot_as_file('./screen.png')
 
# 定位验证码的位置
location = driver.find_element_by_id('login_yzm_img').location
size = driver.find_element_by_id('login_yzm_img').size
left = location['x']
top =  location['y']
right = location['x'] + size['width']
bottom = location['y'] + size['height']
 
# 裁剪保存
img = Image.open('./screen.png').crop((left,top,right,bottom))
img.save('./code.png')
 
driver.quit()

二、滑动验证码

  • 滑动验证码,通常是两个滑块图片,将小图片滑动到大图片上的缺口位置,进行重合,即可通过验证
  • 对于滑动验证码,我们就要识别大图上面的缺口位置,然后让小滑块滑动响应的位置距离,即可
  • 而为了让你滑动起来,更加的拟人化,你需要一个滑动的路径,模拟人为去滑动,而不是机器去滑动

python自动化操作之动态验证码、滑动验证码的降噪和识别

# 下载两个滑块
bg = self.driver.find_element_by_xpath('//*[@id="captcha_container"]/div/div[2]/img[1]').get_attribute('src')
slider = self.driver.find_element_by_xpath('//*[@id="captcha_container"]/div/div[2]/img[2]').get_attribute('src')
 
request.urlretrieve(bg, os.getcwd() + '/bg.png')
request.urlretrieve(slider, os.getcwd() + '/slider.png')
 
 
# 获取两个滑块偏移量方法
def getGap(self, sliderImage, bgImage):
    '''
    Get the gap distance
    :param sliderImage: the image of slider
    :param bgImage: the image of background
    :return: int
    '''
    bgImageInfo = cv2.imread(bgImage, 0)
    bgWidth, bgHeight = bgImageInfo.shape[::-1]
    bgRgb = cv2.imread(bgImage)
    bgGray = cv2.cvtColor(bgRgb, cv2.COLOR_BGR2GRAY)
 
    slider = cv2.imread(sliderImage, 0)
    sliderWidth, sliderHeight = slider.shape[::-1]
 
    res = cv2.matchTemplate(bgGray, slider, cv2.TM_CCOEFF)
    a, b, c, d = cv2.minMaxLoc(res)
    # print(a,b,c,d)
    # 正常如下即可
    # return c[0] if abs(a) >= abs(b) else d[0]
    # 但是头条显示验证码的框跟验证码本身的像素不一致,所以需要根据比例计算
    if abs(a) >= abs(b):
        return c[0] * bgWidth / (bgWidth - sliderWidth)
    else:
        return d[0] * bgWidth / (bgWidth - sliderWidth)
 
# 移动路径方法
def getTrack(self, distance):
    '''
    Get the track by the distance
    :param distance: the distance of gap
    :return: list
    '''
    # 移动轨迹
    track = []
    # 当前位移
    current = 0
    # 减速阈值
    mid = distance * 4 / 5
    # 计算间隔
    t = 0.2
    # 初速度
    v = 0
 
    while current < distance:
        if current < mid:
            # 加速度为正2
            a = 2
        else:
            # 加速度为负3
            a = -3
        # 初速度v0
        v0 = v
        # 当前速度v = v0 + at
        v = v0 + a * t
        # 移动距离x = v0t + 1/2 * a * t^2
        move = v0 * t + 1 / 2 * a * t * t
        # 当前位移
        current += move
        # 加入轨迹
        track.append(round(move))
    return track
 
 
# 滑动到缺口位置
def moveToGap(self, track):
    '''
    Drag the mouse to gap
    :param track: the track of mouse
    :return: None
    '''
    ActionChains(self.driver).click_and_hold(self.driver.find_element_by_xpath('//*[@id="captcha_container"]/div/div[3]/div[2]/div[2]/div')).perform()
    while track:
        x = random.choice(track)
        ActionChains(self.driver).move_by_offset(xoffset=x, yoffset=0).perform()
        track.remove(x)
    time.sleep(0.5)
    ActionChains(self.driver).release().perform()

三、验证码的降噪

验证码的降噪,只是为了处理验证码图像上的多余的线条和干扰线,让你后期识别更加的准确,提高识别的准确度

第一步:可以进行灰度转化

python自动化操作之动态验证码、滑动验证码的降噪和识别

python自动化操作之动态验证码、滑动验证码的降噪和识别

img = cv2.imread('yzm.png')
# 将图片灰度化处理,降维,加权进行灰度化c
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
cv2.imshow('min_gray',gray)
 
cv2.waitKey(0)
cv2.destroyAllWindows()

第二步: 二值化处理

python自动化操作之动态验证码、滑动验证码的降噪和识别

import cv2
 
img = cv2.imread('yzm.png')
# 将图片灰度化处理,降维,加权进行灰度化c
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
 
t,gray2 = cv2.threshold(gray,220,255,cv2.THRESH_BINARY)
 
cv2.imshow('threshold',gray2)
 
cv2.waitKey(0)
cv2.destroyAllWindows()

第三步:噪点过滤

python自动化操作之动态验证码、滑动验证码的降噪和识别

import cv2
 
img = cv2.imread('yzm.png')
# 将图片灰度化处理,降维,加权进行灰度化c
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
 
t,gray2 = cv2.threshold(gray,220,255,cv2.THRESH_BINARY)
 
def remove_noise(img, k=4):
    img2 = img.copy()
 
    #     img处理数据,k过滤条件
    w, h = img2.shape
 
    def get_neighbors(img3, r, c):
        count = 0
        for i in [r - 1, r, r + 1]:
            for j in [c - 1, c, c + 1]:
                if img3[i, j] > 10:  # 纯白色
                    count += 1
        return count
 
    #     两层for循环判断所有的点
    for x in range(w):
        for y in range(h):
            if x == 0 or y == 0 or x == w - 1 or y == h - 1:
                img2[x, y] = 255
            else:
                n = get_neighbors(img2, x, y)  # 获取邻居数量,纯白色的邻居
                if n > k:
                    img2[x, y] = 255
    return img2
 
 
result = remove_noise(gray2)
cv2.imshow('8neighbors', result)
 
cv2.waitKey(0)
cv2.destroyAllWindows()

四、验证码的识别

通常我们会使用tesserocr识别验证码,但是这个库有很大的局限性,识别率低,即时降噪效果很好,有很少的线条,也会不准确,这种识别方式并不十分推荐

所以我们一般会使用第三方的接口进行识别,比如阿里的图片识别、腾讯也都是有的

这些第三方接口需要自己接入识别接口

#识别降噪后的图片
code = tesserocr.image_to_text(nrImg)
 
#消除空白字符
code.strip()
 
#打印
print(code)

总结

到此这篇关于python自动化操作之动态验证码、滑动验证码的降噪和识别的文章就介绍到这了,更多相关python动态验证码降噪和识别内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
Python实现简单拆分PDF文件的方法
Jul 30 Python
Python实现调度算法代码详解
Dec 01 Python
Python unittest模块用法实例分析
May 25 Python
Python 对输入的数字进行排序的方法
Jun 23 Python
使用pandas read_table读取csv文件的方法
Jul 04 Python
python2.7 安装pip的方法步骤(管用)
May 05 Python
使用python3调用wxpy模块监控linux日志并定时发送消息给群组或好友
Jun 05 Python
使用批处理脚本自动生成并上传NuGet包(操作方法)
Nov 19 Python
python 实现单通道转3通道
Dec 03 Python
Python pip安装第三方库实现过程解析
Jul 09 Python
django restframework serializer 增加自定义字段操作
Jul 15 Python
Django项目在pycharm新建的步骤方法
Mar 02 Python
Python图片验证码降噪和8邻域降噪
Aug 30 #Python
Python音乐爬虫完美绕过反爬
Aug 30 #Python
详解解Django 多对多表关系的三种创建方式
Aug 23 #Python
一些让Python代码简洁的实用技巧总结
Aug 23 #Python
一篇文章搞懂python混乱的切换操作与优雅的推导式
Aug 23 #Python
Python学习开发之图形用户界面详解
Aug 23 #Python
利用Python读取微信朋友圈的多种方法总结
Aug 23 #Python
You might like
ThinkPHP3.1新特性之命名范围的使用
2014/06/19 PHP
php之Smarty模板使用方法示例详解
2014/07/08 PHP
php上传文件并显示上传进度的方法
2015/03/24 PHP
php微信浏览器分享设置以及回调详解
2016/08/01 PHP
php die()与exit()的区别实例详解
2016/12/03 PHP
jquery删除数据记录时的弹出提示效果
2014/05/06 Javascript
jqueryUI里拖拽排序示例分析
2015/02/26 Javascript
js图片翻书效果代码分享
2015/08/20 Javascript
jquery.validate 自定义验证方法及validate相关参数
2016/01/18 Javascript
jquery实现弹窗功能(窗口居中显示)
2017/02/27 Javascript
javascript数据结构中栈的应用之符号平衡问题
2017/04/11 Javascript
JavaScript 自定义事件之我见
2017/09/25 Javascript
微信小程序websocket实现聊天功能
2020/03/30 Javascript
axios实现文件上传并获取进度
2020/03/25 Javascript
echarts实现折线图的拖拽效果
2019/12/19 Javascript
JavaScript Window窗口对象属性和使用方法
2020/01/19 Javascript
element 中 el-menu 组件的无限极循环思路代码详解
2020/04/26 Javascript
Vue 数据绑定的原理分析
2020/11/16 Javascript
Python统计纯文本文件中英文单词出现个数的方法总结【测试可用】
2018/07/25 Python
在pandas多重索引multiIndex中选定指定索引的行方法
2018/11/16 Python
python无限生成不重复(字母,数字,字符)组合的方法
2018/12/04 Python
Python3多线程基础知识点
2019/02/19 Python
Python函数的参数常见分类与用法实例详解
2019/03/30 Python
中国综合性网上购物商城:当当(网上卖书起家)
2016/11/16 全球购物
New Balance天猫官方旗舰店:始于1906年,百年慢跑品牌
2017/11/15 全球购物
Fossil加拿大官网:化石手表、手袋、首饰及配饰
2019/04/23 全球购物
编辑求职信样本
2013/12/16 职场文书
建筑个人求职信范文
2014/01/25 职场文书
2014学年自我鉴定
2014/02/23 职场文书
销售岗位职责范本
2014/06/12 职场文书
美容院合作经营协议书
2014/10/10 职场文书
部门2015年度工作总结
2015/04/29 职场文书
胡桃夹子观后感
2015/06/11 职场文书
酒桌上的祝酒词
2015/08/12 职场文书
Python Django搭建文件下载服务器的实现
2021/05/10 Python
各国货币符号大全
2022/02/17 杂记