自动化测试过程中,经常会用到鼠标事件,在selenium的action_chains模块的ActionChains定义了鼠标操作的一些事件,要使用ActionChains类中的方法,首先需要对ActionChains类进行实例化,该类的构造函数参数为driver,实例化后,可以调用它里面的方法。
ActionChains类的方法列表:
click(on_element=None) ——单击鼠标左键
click_and_hold(on_element=None) ——点击鼠标左键,不松开
context_click(on_element=None) ——点击鼠标右键
double_click(on_element=None) ——双击鼠标左键
drag_and_drop(source, target) ——拖拽到某个元素然后松开
drag_and_drop_by_offset(source, xoffset, yoffset) ——拖拽到某个坐标然后松开
key_down(value, element=None) ——按下某个键盘上的键
key_up(value, element=None) ——松开某个键
move_by_offset(xoffset, yoffset) ——鼠标从当前位置移动到某个坐标
move_to_element(to_element) ——鼠标移动到某个元素
move_to_element_with_offset(to_element, xoffset, yoffset) ——移动到距某个元素(左上角坐标)多少距离的位置
perform() ——执行链中的所有动作
release(on_element=None) ——在某个元素位置松开鼠标左键
send_keys(*keys_to_send) ——发送某个键到当前焦点的元素
send_keys_to_element(element, *keys_to_send) ——发送某个键到指定元素
以百度首页的搜索设置为例,首先是悬停在搜索菜单,显示搜索设置后点击操作。实现代码如下:
#导入action_chains的ActionChains类
from selenium.webdriver.common.action_chains import ActionChains
from selenium import webdriver
import time
driver = webdriver.Chrome()
driver.maximize_window()
driver.implicitly_wait(30)
driver.get("http://www.baidu.com")
#对ActionChains进行实例化
actionchains = ActionChains(driver)
locator=driver.find_element_by_css_selector('#u1 > a.pf')
#鼠标悬停到设置
actionchains.move_to_element(locator).perform()
#点击搜索设置
driver.find_element_by_xpath('//*[@id="wrapper"]/div[6]/a[1]').click()
time.sleep(3)
driver.quit()