实现效果
示例代码
import time
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
service = Service(r"D:\software\chromedriver.exe")
driver = webdriver.Chrome(service=service)
# 控制浏览器访问url地址
driver.get("https://www.taobao.com/")
# 隐式等待
driver.implicitly_wait(1)
account = 'account' # 账号
password = 'abc123' # 密码
# 找到“登录”位置
driver.find_element(by=By.CSS_SELECTOR, value="div.member-ft > div > a.btn-login").click()
driver.maximize_window()
driver.implicitly_wait(1)
# 切换页面 获取当前页面handle 获取所有页面的handle 列表的后面
driver.switch_to.window(driver.window_handles[1])
# 找到“账号名”输入框
el_account = driver.find_element(by=By.CSS_SELECTOR, value='#fm-login-id')
print(el_account.text)
driver.implicitly_wait(1)
# 点击账号输入框
el_account.click()
# 输入账号
el_account.send_keys(account)
driver.implicitly_wait(1)
# 找到“密码”输入框
el_password = driver.find_element(by=By.XPATH, value='//*[@id="fm-login-password"]')
# print(el_password.text)
# print(el_password.location)
# 点击密码输入框
el_password.click()
# 输入密码
el_password.send_keys(password)
driver.implicitly_wait(2)
# 找到“登录”按钮,并点击
el_login_btn = driver.find_element(by=By.XPATH, value='//*[@id="login-form"]/div[4]/button')
el_login_btn.click()
# print(el_login_btn.location)
driver.implicitly_wait(1)
# 切换frame
driver.switch_to.frame('baxia-dialog-content')
# 找到滑块,获取宽高
el1 = driver.find_element(by=By.XPATH, value='//*[@id="nc_1_n1z"]')
print(el1.size['width'])
print(el1.size['height'])
# 找到拖动区域,获得宽高
el2 = driver.find_element(by=By.XPATH, value='//*[@id="nc_1__scale_text"]')
print(el2.size['width'])
print(el2.size['height'])
driver.implicitly_wait(2)
# 创建一个事件链对象
chains = ActionChains(driver)
# 实现滑块拖动
chains.drag_and_drop_by_offset(el1, el2.size['width'], -el2.size['height'])
# 事件提交
chains.perform()
time.sleep(5)
# 关闭浏览器
driver.close()
driver.quit()
方法补充
在做登录测试时,有些站点会有“滑块”验证功能,自动化测试可用对滑块拖拉操作的方式处理:
需求:携程注册“滑块”操作
思路:
按住左边滑块
拖放到最右边
用键盘事件中:drag_and_drop_by_offset
代码为:
#大牛测试:轻轻松松自动化
#QQ:2574674466
#专注自动化测试技术传播
from selenium import webdriver
import time
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
driver = webdriver.Chrome()
driver.get("https://passport.ctrip.com/user/reg/home")
driver.find_element_by_css_selector("#agr_pop > div.pop_footer > a.reg_btn.reg_agree").click()
sour = driver.find_element_by_css_selector("#slideCode > div.cpt-drop-box > div.cpt-drop-btn")
print(sour.size['width'])
print(sour.size['height'])
ele =driver.find_element_by_css_selector("#slideCode > div.cpt-drop-box > div.cpt-bg-bar")
print(ele.size['width'])
print(ele.size['height'])
time.sleep(2)
ActionChains(driver).drag_and_drop_by_offset(sour,ele.size["width"],-ele.size["height"]).perform()
到此这篇关于Python+Selenium实现网站滑块拖动操作的文章就介绍到这了,更多相关Python Selenium滑块拖动内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!