人类频繁的用手操作鼠标和键盘,为了解决这个问题,selenium给我们提供了一个类来处理这些事件——ActionChains,ActionChains可以完成鼠标移动,鼠标点击事件,键盘输入,内容菜单交互等交互行为。本节我们先了解下这个类,具体鼠标操作使用案例可查看
selenium鼠标操作
,按键操作案例可查看
selenium键盘操作
。
selenium.webdriver.common.action_chains.ActionChains(driver)
先从从概念上认识下ActionChains:
ActionChains代替人类之手去模拟鼠标操作,比如单击、双击、点击右键、拖拽、长按等动作。
实际上调用ActionChains的方法时,不会立即执行鼠标操作,而是会将所有的操作按顺序存放在一个队列里,最终调用perform()方法时,队列中的操作会依次执行。
换句话说,ActionChains 提供了对动作的链式操作,也就是可以生成一个操作的队列,将复杂的操作过程分解成单个操作,然后组合起来一次性执行。
我们看官方文档的示例:
ActionChains can be used in a chain pattern:
menu = driver.find_element_by_css_selector(".nav")
hidden_submenu = driver.find_element_by_css_selector(".nav #submenu1")
ActionChains(driver).move_to_element(menu).click(hidden_submenu).perform()
Or actions can be queued up one by one, then performed.:
menu = driver.find_element_by_css_selector(".nav")
hidden_submenu = driver.find_element_by_css_selector(".nav #submenu1")
actions = ActionChains(driver)
actions.move_to_element(menu)
actions.click(hidden_submenu)
actions.perform()
【但是如果只是为了鼠标滚动实现网页下拉,那么直接selenium执行js比较简单】。详情查看
selenium滚动鼠标下拉网页
概念是抽象的,要用实例来说明,但是限于篇幅本篇就先把ActionChains方法罗列下,后面的文章用实例来操作。
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) ——发送某个键到指定元素