本文总结了Selenium常用的鼠标操作。
1、鼠标点击
打开百度网站,点击首页的新闻。
from selenium import webdriver
from time import sleep
driver = webdriver.Chrome()
driver.get('https://www.baidu.com/')
ele = driver.find_element_by_link_text('新闻')
ele.click() # 鼠标单击
sleep(2)
driver.quit()
2、内置鼠标操作包
WebDriver封装了一套鼠标操作的包,
●引入包:from selenium.webdriver.common.action_chains import ActionChains。
●定位元素,存储到某个变量:ele = driver.find_element_by_×××('××')。
●固定写法:ActionChains(driver).click(ele).perform()
重写例子
from selenium import webdriver
from time import sleep
from selenium.webdriver.common.action_chains import ActionChains
driver = webdriver.Chrome()
driver.get('https://www.baidu.com/')
ele = driver.find_element_by_link_text('新闻')
ActionChains(driver).click(ele).perform()
sleep(2)
driver.quit()
3、鼠标双击操作
from selenium import webdriver
from time import sleep
from selenium.webdriver.common.action_chains import ActionChains
driver = webdriver.Chrome()
driver.get("http://sahitest.com/demo/clicks.htm")
ele = driver.find_element_by_xpath('/html/body/form/input[2]')
sleep(2)
# 通过double_click方法来模拟鼠标双击的操作
ActionChains(driver).double_click(ele).perform()
sleep(3)
driver.quit()
“http://sahitest.com/demo/”这个网址简直是练习操作控件的“神器”,笔者整理了各种Web控件用于练习定位及操作,后续我们会有大量的测试代码源于该网站。
4、鼠标右击
from selenium import webdriver
from time import sleep
from selenium.webdriver.common.action_chains import ActionChains
driver = webdriver.Chrome()
driver.get("http://sahitest.com/demo/clicks.htm")
ele = driver.find_element_by_xpath('/html/body/form/input[4]')
sleep(2)
# 通过context_click方法模拟鼠标右击的操作
ActionChains(driver).context_click(ele).perform()
sleep(3)
driver.quit()
5、鼠标指针悬浮
from selenium import webdriver
from time import sleep
from selenium.webdriver.common.action_chains import ActionChains
driver = webdriver.Chrome()
driver.get("http://sahitest.com/demo/mouseover.htm")
ele = driver.find_element_by_xpath('/html/body/form/input[1]')
sleep(2)
# 通过move_to_element方法模拟鼠标指针的悬浮操作
ActionChains(driver).move_to_element(ele).perform()
sleep(3)
driver.quit()
6、鼠标拖动
from selenium import webdriver
from time import sleep
from selenium.webdriver.common.action_chains import ActionChains
driver = webdriver.Chrome()
driver.get("http://sahitest.com/demo/dragDropMooTools.htm")
source = driver.find_element_by_xpath('//*[@id="dragger"]')
target = driver.find_element_by_xpath('/html/body/div[5]')
sleep(2)
# 通过drag_and_drop方法模拟鼠标拖动操作
ActionChains(driver).drag_and_drop(source, target).perform()
sleep(3)
driver.quit()
7、鼠标操作汇总