使用 OpenCV 破解滑块验证教程
滑块验证码是一种常见的反自动化机制,通常用于防止机器人操作。本教程将指导你如何使用 OpenCV 和 Playwright 破解滑块验证码。我们将通过以下步骤实现:
- 获取滑块和背景图片
- 计算滑块缺口位置
- 生成滑动轨迹
- 模拟滑块滑动
- 处理验证码
1. 环境准备
首先,确保你已经安装了以下 Python 库:
pip install opencv-python-headless numpy playwright
2. 获取滑块和背景图片
使用 Playwright 打开目标网页,并获取滑块和背景图片的 Base64 编码。
from playwright.sync_api import sync_playwright
import cv2
import numpy as np
def decode_base64_image(base64_string):
import base64
from io import BytesIO
if base64_string.startswith("data:image"):
base64_string = base64_string.split(",")[1]
img_data = base64.b64decode(base64_string)
img_array = np.frombuffer(img_data, dtype=np.uint8)
img = cv2.imdecode(img_array, cv2.IMREAD_COLOR)
return img
def get_images(page):
# 填入背景图片xpath地址
bg_img = page.locator('xpath=')
# 填入滑块图片xpath地址
slide_block = page.locator('xpath=')
bg_img_base64 = bg_img.get_attribute("src")
slide_block_base64 = slide_block.get_attribute("src")
bg_img_decoded = decode_base64_image(bg_img_base64)
slide_block_decoded = decode_base64_image(slide_block_base64)
return bg_img_decoded, slide_block_decode