滑动滑块的两个关键点为:(1)生成滑动轨迹(2)控制滑动按钮进行滑动
(1)根据要滑动的距离生成滑动轨迹,此处是模拟人为滑动:先加速滑动滑块,再减速滑动滑块。代码如下:
其中distance参数就是要滑动的距离,返回值tracks为生成的滑动轨迹,,后面要把tracks传给滑动滑块的函数。
def get_tracks(self, distance):
"""
根据偏移量获取移动轨迹
:param distance:偏移量
:return:移动轨迹
"""
# 移动轨迹
tracks = []
# 当前位移
current = 0
# 减速阈值
mid = distance * 4 / 5
# 计算间隔
t = 0.2
# 初速度
v = 0
while current < distance:
if current < mid:
# 加速度为正2
a = 5
else:
# 加速度为负3
a = -3
# 初速度v0
v0 = v
# 当前速度
v = v0 + a * t
# 移动距离
move = v0 * t + 1 / 2 * a * t * t
# 当前位移
current += move
# 加入轨迹
tracks.append(round(move))
return tracks
2)控制滑动按钮进行滑动,代码如下:
其中slider就是获取到的滑块按钮,tracks就是上面(1)中的函数返回的滑动轨迹。
def move_to_gap(self, slider, tracks):
"""
拖动滑块
:param slider: 滑块
:param tracks: 轨迹
:return:
"""
# 模拟滑动滑块
action = ActionChains(self.browser)
action.click_and_hold(slider).perform()
# action.reset_actions() # 清除之前的action
for i in tracks:
action.move_by_offset(xoffset=i, yoffset=0).perform()
time.sleep(0.5)
action.release().perform()
3)使用示例:
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver import ActionChains
from selenium.webdriver.support import expected_conditions as EC
class seleniumLogin()
def __init__(self, timeout=20):
self.timeout = timeout
self.browser = webdriver.Chrome()
self.browser.maximize_window()
self.wait = WebDriverWait(self.browser, self.timeout)
def login(self):
#....其他代码....
# 获取滑动滑块
slide = self.wait.until(
EC.element_to_be_clickable((By.CSS_SELECTOR,
'div#nc_1__scale_text > span.nc-lang-cnt'))
)
# 获取滑块滑动距离
distance = slide.size['width']
# 生成滑动轨迹
tracks = self.get_tracks(self, distance):
# 获取滑块点击按钮
slide_button = self.wait.until(
EC.element_to_be_clickable((By.CSS_SELECTOR,
'span#nc_1_n1z'))
)
# 滑动滑块进行验证
self.move_to_gap(slide_button , tracks)