python解决滑动验证码方案
1.获取需要滑动的图片
import base64
if safe_query(page, '//*[contains(text(),"向右滑动完成验证")]'): target_img = safe_query(page, '//*[@class="verify-sub-block"]/img') if not target_img: continue target_b64 = target_img.get_attribute("src").split(";base64,", 1)[-1] target_bytes = base64.b64decode(target_b64.encode())
2.获取滑动背景图片
background_img = safe_query(page, '//*[@class="verify-img-panel"]/img') if not background_img: continue background_b64 = background_img.get_attribute("src").split(";base64,", 1)[-1] background_bytes = base64.b64decode(background_b64.encode())
3.计算滑块与目标位置距离
import cv2 import numpy import numpy as np from io import BytesIO def match_slider_from_bytes(bg_bytes: bytes, slider_bytes: bytes, debug=False) -> int: bg_array = np.frombuffer(bg_bytes, np.uint8) slider_array = np.frombuffer(slider_bytes, np.uint8) bg = cv2.imdecode(bg_array, cv2.IMREAD_GRAYSCALE) slider = cv2.imdecode(slider_array, cv2.IMREAD_GRAYSCALE) # 边缘检测 bg_edge = cv2.Canny(bg, 100, 200) slider_edge = cv2.Canny(slider, 100, 200) # 模板匹配 result = cv2.matchTemplate(bg_edge, slider_edge, cv2.TM_CCOEFF_NORMED) _, max_val, _, max_loc = cv2.minMaxLoc(result) return max_loc[0] # 返回x坐标 distance = match_slider_from_bytes(background_bytes, target_bytes, False) ii = "距离:{}".format(distance) print(ii)
- 核心流程:字节数据→NumPy 数组→灰度图→边缘检测→模板匹配→提取 X 坐标,全程围绕 “精准找到滑块位置” 展开。
- 关键优化:转灰度图 + 边缘检测,剔除了颜色、亮度等干扰因素,让模板匹配只关注滑块的轮廓特征,准确率更高。
- 适用场景:主要用于自动化操作中破解滑块验证码,返回的 X 坐标可直接用于控制滑块拖动的距离。
4.模拟人为滑动
def human_like_drag(page, slider, distance: int): box = slider.bounding_box() if box is None: raise Exception("未能获取滑块坐标") start_x = box["x"] + box["width"] / 2 start_y = box["y"] + box["height"] / 2 page.mouse.move(start_x, start_y) page.mouse.down() current_x = start_x total_steps = 3 for i in range(total_steps): step = (distance / total_steps) * random.uniform(0.9, 1.1) current_x += step jitter_y = start_y + random.uniform(-0.5, 0.5) page.mouse.move(current_x, jitter_y) time.sleep(random.uniform(0.01, 0.03)) page.mouse.up() slider_block = safe_query(page, '//*[@class="verify-move-block"]') if not slider_block: continue human_like_drag(page, slider_block, distance)
- 核心设计思路:通过 “中心点击 + 分步滑动 + 随机步长 + Y 轴抖动 + 微小停顿”,模拟真人操作特征,避免被反爬风控识别。
- 关键细节:所有随机值(步长、抖动、停顿)都是为了打破机器的 “规律性”,贴近人类操作的 “不规整性”。
- 依赖环境:需要导入
random和time库,且page对象需是 Playwright/Puppeteer 等支持mouse操作的自动化对象。
5.如果不成功,整个步骤可以循环几次

浙公网安备 33010602011771号