Selenium中对滑块的操作基本是采用元素拖拽的方式,而这种方式需要用到Selenium的Actionchains功能模块的drag_and_drop_by_offset方法
drag_and_drop_by_offset(source,xoffset,yoffset)
source:鼠标拖动的原始元素
xoffset:鼠标把元素拖动到另一个位置的x坐标
yoffset:鼠标把元素拖动到另一个位置的y坐标
思路:1. 获取滑块元素,求出滑块的长度和宽度
获取滑块区域元素,求出其长度和宽度
2. 使用drag_and_drop_by_offset方法移动滑块到滑块区域的最大长度及宽度
以携程网登录页面举例
"""实现携程网站的登录功能"""
from seleniumimport webdriver
import time
from selenium.webdriver.common.action_chainsimport ActionChains
driver = webdriver.Chrome("C:/Users/Administrator/PycharmProjects/untitled/chromedriver.exe")
driver.implicitly_wait(30)
driver.get("https://www.ctrip.com/?sid=155952&allianceid=4897&ouid=index")
driver.maximize_window()
# 点击登录
driver.find_element_by_css_selector("#nav-bar-set-login > a > span").click()
# 登录账号
account =123
driver.find_element_by_id('nloginname').send_keys(account)
# 登录密码
password ="***"
driver.find_element_by_id('npwd').send_keys(password)
# 拖动滑块
slider = driver.find_element_by_css_selector("#sliderddnormal > div.cpt-drop-box > div.cpt-drop-btn")
# print(slider.size['width']) 方便理解,打印出来40px
# print(slider.size['height']) 打印出来40px
slider_area = driver.find_element_by_css_selector("#sliderddnormal > div.cpt-drop-box > div.cpt-bg-bar")
# print(slider_area.size['width']) 打印出来288px
# print(slider_area.size['height']) 打印出来40px
ActionChains(driver).drag_and_drop_by_offset(slider,slider_area.size['width'],slider.size['height']).perform()
time.sleep(3)