滑块验证码是网站常用的反爬机制之一,核心逻辑是让用户拖动滑块将缺口拼合到正确位置,以此验证操作者为真实用户。使用Python结合Selenium和OpenCV可以自动完成这一流程,无需人工干预。
环境准备
首先需要安装对应的依赖库,执行以下命令完成安装:
pip install selenium opencv-python numpy pillow
同时需要下载对应浏览器的驱动,比如Chrome浏览器需要下载ChromeDriver,确保驱动版本和浏览器版本匹配,并将驱动路径配置到系统环境变量中。
获取验证码图片
使用Selenium打开目标页面,定位到滑块验证码的相关元素,分别获取背景图和缺口图的截图。需要注意部分网站的验证码图片是拼接或者带有干扰元素的,需要先裁剪出有效的图片区域。
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
from PIL import Image
# 初始化浏览器
driver = webdriver.Chrome()
driver.get("目标页面地址")
time.sleep(2)
# 定位背景图和缺口图元素
bg_img = driver.find_element(By.CLASS_NAME, "bg-img-class")
gap_img = driver.find_element(By.CLASS_NAME, "gap-img-class")
# 截取整个页面截图
driver.save_screenshot("page.png")
page_pic = Image.open("page.png")
# 裁剪背景图
bg_location = bg_img.location
bg_size = bg_img.size
bg_box = (bg_location["x"], bg_location["y"], bg_location["x"] + bg_size["width"], bg_location["y"] + bg_size["height"])
bg_pic = page_pic.crop(bg_box)
bg_pic.save("bg.png")
# 裁剪缺口图
gap_location = gap_img.location
gap_size = gap_img.size
gap_box = (gap_location["x"], gap_location["y"], gap_location["x"] + gap_size["width"], gap_location["y"] + gap_size["height"])
gap_pic = page_pic.crop(gap_box)
gap_pic.save("gap.png")
OpenCV计算缺口距离
通过OpenCV处理两张图片,识别缺口的位置,计算需要拖动的距离。通常的处理思路是将两张图片转换为灰度图,再计算差异,找到缺口的偏移位置。
import cv2
import numpy as np
def get_gap_distance(bg_path, gap_path):
# 读取图片
bg = cv2.imread(bg_path)
gap = cv2.imread(gap_path)
# 转换为灰度图
bg_gray = cv2.cvtColor(bg, cv2.COLOR_BGR2GRAY)
gap_gray = cv2.cvtColor(gap, cv2.COLOR_BGR2GRAY)
# 计算差异
diff = cv2.absdiff(bg_gray, gap_gray)
# 二值化处理
_, thresh = cv2.threshold(diff, 50, 255, cv2.THRESH_BINARY)
# 查找轮廓
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# 找到最大的轮廓,即为缺口位置
max_contour = max(contours, key=cv2.contourArea)
x, y, w, h = cv2.boundingRect(max_contour)
# 返回缺口的x坐标,即为需要拖动的距离
return x
distance = get_gap_distance("bg.png", "gap.png")
print(f"计算得到缺口距离:{distance}像素")
模拟人类拖动轨迹
直接匀速拖动滑块很容易被识别为机器操作,需要模拟人类的拖动轨迹,通常轨迹是先快后慢,中间可能有小幅波动,符合人类操作的物理特征。
import random
def get_track(distance):
track = []
current = 0
# 减速阈值,超过这个距离后开始减速
mid = distance * 3 / 5
# 每次移动的间隔
t = 0.2
# 初始速度
v = 0
while current < distance:
if current < mid:
# 加速度为正,速度增加
a = random.randint(2, 5)
else:
# 加速度为负,速度减小
a = -random.randint(2, 5)
# 计算当前速度
v0 = v
v = v0 + a * t
# 计算移动距离
move = v0 * t + 0.5 * a * t * t
# 取整,避免小数
move = round(move)
current += move
track.append(move)
# 如果最后移动距离超过目标距离,调整最后一个值
if current > distance:
track[-1] = track[-1] - (current - distance)
return track
track = get_track(distance)
print(f"生成的拖动轨迹:{track}")
执行滑块拖动操作
使用Selenium定位滑块元素,按照生成的轨迹依次拖动滑块,完成验证操作。
from selenium.webdriver.common.action_chains import ActionChains
# 定位滑块元素
slider = driver.find_element(By.CLASS_NAME, "slider-class")
# 创建动作链
action = ActionChains(driver)
# 点击并按住滑块
action.click_and_hold(slider).perform()
time.sleep(0.5)
# 按照轨迹移动
for move in track:
action.move_by_offset(move, 0).perform()
time.sleep(random.uniform(0.01, 0.03))
# 松开滑块
action.release().perform()
time.sleep(2)
# 验证是否通过,可根据页面反馈判断
print("滑块拖动完成")
# 关闭浏览器
driver.quit()
注意事项
- 部分网站的验证码图片带有干扰线条或者阴影,需要调整OpenCV处理的阈值参数,提高缺口识别的准确率。
- 拖动轨迹的参数可以根据实际情况调整,尽量模拟不同用户的操作习惯,降低被识别的概率。
- 如果验证码有刷新机制,需要在获取图片前等待验证码加载完成,避免获取到不完整的图片。
- 部分网站会对Selenium的特征进行检测,需要配置浏览器参数隐藏自动化特征,提升通过率。