打开对应网站,走到滑块验证处 ;
设置显性等待,找到滑块图片加载完毕 WebDriverWait.until;
class yanzhengma:
def __init__(self):
self.url = 'https://passport.xfyun.cn/login'
self.browser = webdriver.Chrome()
self.browser.maximize_window()
self.wait = WebDriverWait(self.browser, 5)
self.success = False
self.try_num = 2
self.now_num = 2
self.flesh_num = 1
def run(self):
self.browser.get(self.url)
获取图片上下左右边距离窗口的位置 img.location img.size;
def get_position(self):
"""
获取验证码位置
:return: 验证码位置元组
"""
img = self.wait.until(EC.presence_of_element_located((By.CLASS_NAME, 'geetest_canvas_img')))
time.sleep(1)
location = img.location
size = img.size
top, bottom, left, right = location['y'], location['y'] + size['height'], location['x'], location['x'] + size['width']
return top, bottom, left, right
截取滑块验证的图片 driver.get_screenshot_as_png();
screenshot = self.browser.get_screenshot_as_png()
读取图片的RGB顺序,并切割 Image.open Image.crop;
screenshot = Image.open(BytesIO(screenshot))
获取缺口的偏移量;
def get_gap(self, image):
"""
获取缺口偏移量
:param image: 带缺口图片
:return:
"""
for i in [10 * i for i in range(1, 14)]:
for j in range(50, image.size[0] - 30):
if self.is_pixel_equal(image, j, i):
break
return left_list
判断缺口偏移量;
@staticmethod
def is_pixel_equal(image, x, y):
"""
判断两个像素是否相同
:param image: 图片
:param x: 位置x
:param y: 位置y
:return: 像素是否相同
"""
x_max = image.size[0]
# 取两个图片的像素点
pixel1 = image.load()[x, y]
threshold = 150
count = 0
if pixel1[0] < threshold and pixel1[1] < threshold and pixel1[2] < threshold:
for i in range(x + 1, image.size[0]):
piexl = image.load()[i, y]
if piexl[0] < threshold and piexl[1] < threshold and piexl[2] < threshold:
count += 1
else:
break
if int(x_max / 8.6) < count < int(x_max / 4.3):
left_list.append((x, count))
return True
else:
return False
根据偏移量获取移动轨迹;
@staticmethod
def get_track(distance):
"""
根据偏移量获取移动轨迹
:param distance: 偏移量
:return: 移动轨迹
"""
# 移动轨迹
track = []
# 当前位移
current = 0
# 减速阈值
mid = distance * 4 / 5
# 计算间隔
t = 0.2
# 初速度
v = 0
while current < distance:
if current < mid:
# 加速度为正2
a = 2
else:
# 加速度为负3
a = -3
# 初速度v0
v0 = v
# 当前速度v = v0 + at
v = v0 + a * t
# 移动距离x = v0t + 1/2 * a * t^2
move = v0 * t + 1 / 2 * a * t * t
# 当前位移
current += move
# 加入轨迹
track.append(round(move))
return track
获取滑块元素,拖动滑块 ActionChains();
ActionChains(self.browser).click_and_hold(slider).perform()
for x in track:
ActionChains(self.browser).move_by_offset(xoffset=x, yoffset=0).perform()
ActionChains(self.browser).release().perform()
当前实现代码及缺陷:
import time
from io import BytesIO
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from PIL import Image
left_list = []
BORDER_1 = 7
BORDER_2 = 12
class yanzhengma:
def __init__(self):
self.url = 'https://passport.xfyun.cn/login'
self.browser = webdriver.Chrome()
self.browser.maximize_window()
self.wait = WebDriverWait(self.browser, 5)
self.success = False
self.try_num = 2
self.now_num = 2
self.flesh_num = 1
# 获取验证码图片
def get_geetest_image(self, name='captcha.png'):
"""
获取验证码图片
:return: 图片对象
"""
top, bottom, left, right = self.get_position()
print(top, bottom, left, right)
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_position(self):
"""
获取验证码位置
:return: 验证码位置元组
"""
img = self.wait.until(EC.presence_of_element_located((By.CLASS_NAME, 'geetest_canvas_img')))
time.sleep(1)
location = img.location
size = img.size
top, bottom, left, right = location['y'], location['y'] + size['height'], location['x'], location['x'] + size['width']
return top, bottom, left, right
# 获取网页截图
def get_screenshot(self):
"""
获取网页截图
:return: 截图对象
"""
screenshot = self.browser.get_screenshot_as_png()
screenshot = Image.open(BytesIO(screenshot))
return screenshot
# 获取缺口偏移量
def get_gap(self, image):
"""
获取缺口偏移量
:param image: 带缺口图片
:return:
"""
for i in [10 * i for i in range(1, 14)]:
for j in range(50, image.size[0] - 30):
if self.is_pixel_equal(image, j, i):
break
return left_list
# 判断缺口偏移量
@staticmethod
def is_pixel_equal(image, x, y):
"""
判断两个像素是否相同
:param image: 图片
:param x: 位置x
:param y: 位置y
:return: 像素是否相同
"""
x_max = image.size[0]
# 取两个图片的像素点
pixel1 = image.load()[x, y]
threshold = 150
count = 0
if pixel1[0] < threshold and pixel1[1] < threshold and pixel1[2] < threshold:
for i in range(x + 1, image.size[0]):
piexl = image.load()[i, y]
if piexl[0] < threshold and piexl[1] < threshold and piexl[2] < threshold:
count += 1
else:
break
if int(x_max / 8.6) < count < int(x_max / 4.3):
left_list.append((x, count))
return True
else:
return False
# 根据偏移量获取移动轨迹
@staticmethod
def get_track(distance):
"""
根据偏移量获取移动轨迹
:param distance: 偏移量
:return: 移动轨迹
"""
# 移动轨迹
track = []
# 当前位移
current = 0
# 减速阈值
mid = distance * 4 / 5
# 计算间隔
t = 0.2
# 初速度
v = 0
while current < distance:
if current < mid:
# 加速度为正2
a = 2
else:
# 加速度为负3
a = -3
# 初速度v0
v0 = v
# 当前速度v = v0 + at
v = v0 + a * t
# 移动距离x = v0t + 1/2 * a * t^2
move = v0 * t + 1 / 2 * a * t * t
# 当前位移
current += move
# 加入轨迹
track.append(round(move))
return track
# 获取滑块对象
def get_slider(self):
"""
获取滑块
:return: 滑块对象
"""
try:
slider = self.wait.until(EC.element_to_be_clickable((By.CLASS_NAME, 'geetest_slider_button')))
except Exception:
return
return slider
def run(self):
self.browser.get(self.url)
time.sleep(3)
self.browser.find_element_by_xpath('//*[@id="app"]/div/section/div/div/div[2]/div/div[1]/div[2]/div[1]/div/div/div/div/div[1]/div[3]').click()
self.browser.find_element_by_id('username').send_keys('16619942153')
time.sleep(0.5)
self.browser.find_element_by_id('password').send_keys('sj7845464')
time.sleep(0.5)
self.browser.find_element_by_xpath('//*[@id="app"]/div/section/div/div/div[2]/div/div[2]/div/form/button').click()
time.sleep(3)
# while not self.success and self.now_num > 0:
error_list = [5, 7, 10]
for i in range(3):
try:
image = self.get_geetest_image()
except:
break
left_list = self.get_gap(image)
#----------------------------------------------------
x_max = image.size[0]
left_list = sorted(left_list, key=lambda x: abs(x[1] - int(x_max / 6.45)))
print(left_list)
if not left_list:
print("left_lsit为空, 无法获取gap")
break
gap = left_list[0][0]
print('gap:', gap)
# 计算滑动距离
track = self.get_track(int(gap) - error_list[i])
# 拖动滑块
slider = self.get_slider()
print('位移list:', track)
ActionChains(self.browser).click_and_hold(slider).perform()
for x in track:
ActionChains(self.browser).move_by_offset(xoffset=x, yoffset=0).perform()
ActionChains(self.browser).release().perform()
if __name__ == "__main__":
y = yanzhengma()
y.run()
缺陷:
1.存在滑块无法滑到至合适的位置;
2.滑动速度太均匀,需要改变方式模拟人为动作轨迹绕过机器检验。