实现步骤
初始化: 创建一个CrackGeetest类,并初始化链接地址、浏览器对象、等待时间以及登录账户和密码信息。
模拟登录: 使用Selenium模拟登录操作,打开登录页面并输入账户和密码。
获取滑动验证按钮: 使用Selenium定位滑动验证按钮,并点击触发滑动验证码的显示。
获取验证码图片: 使用Selenium截取包含滑动验证码的屏幕截图,并通过图像处理库Pillow获取滑动验证码的图片。
识别缺口位置: 对比两张验证码图片的像素点,找到不一致的像素点位置,即为滑块需要移动的距离。
生成滑块拖动路径: 根据缺口位置计算出滑块需要拖动的路径,以模拟人类的拖动行为。
模拟拖动滑块: 使用Selenium模拟拖动滑块的操作,按照生成的路径拖动滑块完成验证过程。
验证结果处理: 根据验证结果进行相应的操作,例如登录或注册等。
完整代码示例
python
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from PIL import Image
import numpy as np
import time
class CrackGeetest():
def __init__(self):
self.url = 'https://example.com/login'
self.browser = webdriver.Chrome()
self.wait = WebDriverWait(self.browser, 20)
self.email = 'your_email@example.com'
self.password = 'your_password'
def open(self):
self.browser.get(self.url)
email = self.wait.until(EC.presence_of_element_located((By.ID, 'email')))
password = self.wait.until(EC.presence_of_element_located((By.ID, 'password')))
email.send_keys(self.email)
password.send_keys(self.password)
def get_geetest_button(self):
button = self.wait.until(EC.element_to_be_clickable((By.CLASS_NAME, 'geetest_radar_tip')))
return button
def get_geetest_image(self, name='captcha.png'):
img = self.wait.until(EC.presence_of_element_located((By.CLASS_NAME, 'geetest_canvas_img')))
location = img.location
size = img.size
top, bottom, left, right = location['y'], location['y'] + size['height'], location['x'], location['x'] + size['width']
screenshot = self.browser.get_screenshot_as_png()
screenshot = Image.open(BytesIO(screenshot))
captcha = screenshot.crop((left, top, right, bottom))
captcha.save(name)
return captcha
def get_gap(self, image1, image2):
threshold = 60
for i in range(image1.size[0]):
for j in range(image1.size[1]):
pixel1 = image1.load()[i, j]
pixel2 = image2.load()[i, j]
if not self.is_pixel_equal(pixel1, pixel2, threshold):
return i
return 0
def is_pixel_equal(self, pixel1, pixel2, threshold):
return all(abs(p1 - p2) < threshold for p1, p2 in zip(pixel1[:3], pixel2[:3]))
def get_track(self, distance):
return [distance]
def move_to_gap(self, slider, track):
ActionChains(self.browser).click_and_hold(slider).perform()
for x in track:
ActionChains(self.browser).move_by_offset(xoffset=x, yoffset=0).perform()
time.sleep(0.5)
ActionChains(self.browser).release().perform()
def crack(self):
self.open()
button = self.get_geetest_button()
button.click()
image1 = self.get_geetest_image('captcha1.png')
slider = self.wait.until(EC.element_to_be_clickable((By.CLASS_NAME, 'geetest_slider_button')))
slider.click()
image2 = self.get_geetest_image('captcha2.png')
gap = self.get_gap(image1, image2)
gap -= 6
track = self.get_track(gap)
self.move_to_gap(slider, track)
if __name__ == '__main__':
crack = CrackGeetest()
crack.crack()
自动识别滑动验证码的方法