selenium基本使用之鼠标操作
使用ActionChains类中提供的方法实现鼠标点击,拖拽等相关的操作,使用如下:
#driver即浏览器驱动,element被操作的元素对象,perform对整个操作进行提交
#鼠标左击(单击)
ActionChains(driver).click(element).perform()
#鼠标右击
ActionChains(driver).context_click(element).perform()
#鼠标双击
ActionChains(driver).double_click(element).perform()
#鼠标移动
ActionChains(driver).click_and_hold(element).perform()
#鼠标拖拽,source--源元素,target--目标元素
ActionChains(driver).drag_and_drop(source,target).perform()
下面以该http://sahitest.com/demo/网页为例,测试相关操作:
#导入相应的包
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from time import sleep
driver = webdriver.Chrome()
#获取网页
driver.get("http://sahitest.com/demo/")
# 进入鼠标点击操作测试页面
driver.find_element_by_xpath('/html/body/table/tbody/tr/td[5]/a[1]').click()
sleep(5)
# 左击
left_click = driver.find_element_by_xpath('/html/body/form/input[3]')
ActionChains(driver).click(left_click).perform()
sleep(5)
# 右击
right_click = driver.find_element_by_xpath('/html/body/form/input[4]')
ActionChains(driver).context_click(right_click).perform()
sleep(5)
# 双击
db_click = driver.find_element_by_xpath('/html/body/form/input[2]')
ActionChains(driver).double_click(db_click).perform()
sleep(5)
# 返回主页面
driver.back()
sleep(5)
# 找到鼠标移动悬停测试页面
driver.find_element_by_xpath('/html/body/table/tbody/tr/td[5]/a[3]').click()
sleep(3)
# 鼠标悬停
hold_click = driver.find_element_by_xpath('/html/body/a[1]/span')
ActionChains(driver).click_and_hold(hold_click).perform()
sleep(3)
# 鼠标移动
move_click1 = driver.find_element_by_xpath('/html/body/form/input[1]')
ActionChains(driver).move_to_element(move_click1).perform()
sleep(3)
move_click2 = driver.find_element_by_xpath('/html/body/form/input[2]')
ActionChains(driver).move_to_element(move_click2).perform()
sleep(3)
# 返回主页面
driver.back()
sleep(5)
# 找到拖拽测试页面
driver.find_element_by_xpath('/html/body/table/tbody/tr/td[5]/a[5]').click()
sleep(3)
# 鼠标拖拽
# 源元素
source = driver.find_element_by_xpath('//*[@id="dragger"]')
# 目标元素
target = driver.find_element_by_xpath('/html/body/div[2]')
ActionChains(driver).drag_and_drop(source,target).perform()