python验证码识别教程之滑动验证码验证码识别教程之滑动验证码
前言前言
上篇文章记录了2种分割验证码的方法,此外还有一种叫做”滴水算法”(Drop Fall Algorithm)的方法,但本人智商原因看这个算
法看的云里雾里的,所以今天记录滑动验证码的处理吧。网上据说有大神已经破解了滑动验证码的算法,可以不使用selenium
来破解,但本人能力不足还是使用笨方法吧。
基础原理很简单,首先点击验证码按钮后的图片是滑动后的完整结果,点击一下滑块后会出现拼图,对这2个分别截图后比较
像素值来找出滑动距离,并结合selenium来实现拖拽效果。
至于selenium怎么安装就不说了,滑动验证码的一个难点就是要模拟人的拖拽行为,移动快了不行,慢了也不行。
这里以国家企业公示网站为例:这里以国家企业公示网站为例:
# -*- coding: utf-8 -*-
import time
import random
from io import BytesIO
from PIL import Image
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver import ActionChains
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
class Slide(object):
"""滑动验证码破解"""
def __init__(self, target):
self.target = target # 要搜索的公司名称
self.driver = webdriver.Chrome()
self.wait = WebDriverWait(self.driver, 10)
def crop(self, left, top, right, bottom, pic_name):
"""截屏并裁剪"""
ss = Image.open(BytesIO(self.driver.get_screenshot_as_png()))
cp = ss.crop((left, top, right, bottom)) # 注意这里顺序
cp.save(pic_name)
return cp
def calc_move(self, pic1, pic2):
"""根据阈值计算移动距离"""
pix1 = pic1.load()
pix2 = pic2.load()
threshold = 200
move = 0
# 因为滑块都从左向右滑动,而碎片本身宽度为60所以从60开始遍历
for i in range(60, pic1.size[0]):
flag = False
for j in range(pic1.size[1]):
r = abs(pix1[i, j][0] - pix2[i, j][0])
g = abs(pix1[i, j][1] - pix2[i, j][1])
b = abs(pix1[i, j][2] - pix2[i, j][2])
# if r > threshold and g > threshold and b > threshold:
# 方法1:分别判断rgb大于阈值
# flag = True
# break
if r + g + b > threshold:
# 方法2:判断rgb总和跟阈值比较,效果比1好 为什么呢??
flag = True
break
if flag:
move = i
break
return move
def path1(self, distance):
"""绘制移动路径方法1,构造一个等比数列"""
q = 0.4 # 测试后发现0.4效果最佳