Selenium-ActionChains Api接口详解

ActionChains

有时候我们在通过Selenium做UI自动化的时候,明明能够在DOM树内看到这个元素,但是我在通过driver click、sendkey的时候,就是点击不到或无法输入字符串。实际上这是由于WEB中某些元素需要通过一系列连贯的操作才能处于可以点击的状态,driver提供的click方法是每次都只执行一个命令操作,而我们需要连贯的操作。或者经常遇到那种,需要鼠标悬浮后,要操作的元素才会出现的某种场景,那么我们就要模拟鼠标悬浮到某一个位置,做一系列的连贯操作,这里就要应用Selenium提供的ActionChains模块

具体使用方法参考官方文档: https://selenium-python.readthedocs.io/api.html#module-selenium.webdriver.common.action_chains

或某大佬翻译的中文文档:https://python-selenium-zh.readthedocs.io/zh_CN/latest/7.2%20%E8%A1%8C%E4%B8%BA%E9%93%BE/

引入方式

#引入方式一
from selenium.webdriver.common.action_chains import ActionChains
#引入方式二
from selenium.webdriver import ActionChains

实际上ActionChains这个模块的实现的核心思想就是,当你调用ActionChains的方法时,不会立即执行,而是会将所有的操作按顺序存放在一个List里,当你调用perform()方法时,队列中的时间会依次执行。(注:推荐一个尺子工具,MeasulerIt)

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) ——发送某个键到指定元素

 

drag_and_drop(鼠标拖动)

# 将source元素拖放至target元素处,参数为两个elementObj
ActionChains(driver).drag_and_drop(source=source,target=target)
 
# 将一个source元素 拖动到针对source坐上角坐在的x y处 可存在负宽度的情况和负高度的情况
ActionChains(driver).drag_and_drop_by_offset(source, x, y)
 
# 这种也是拖拽的一种方式,都是以源元素的左上角为基准,移动坐标
ActionChains(driver).click_and_hold(dom).move_by_offset(169,188).release().perform()

move_to_element

# 鼠标移动到某一个元素上,结束elementObj
ActionChains(driver).move_to_element(e)
 
# 鼠标移动到制定的坐标上,参数接受x,y
ActionChains(driver).move_by_offset(e['x'],e['y'])
 
例:
driver = webdriver.Chrome()
driver.maximize_window()
driver.get('http://www.baidu.com')
time.sleep(2)
# driver.execute_script('document.body.scrollTop=0')
driver.execute_script('document.documentElement.scrollTop')
time.sleep(1) 
a = driver.find_element_by_id('a').location 
dis = driver.find_element_by_id('dis1') 
ActionChains(driver).move_by_offset(a['x'],a['y']).double_click(dis).perform()

click

# 单击事件,可接受elementObj
ActionChains(driver).click()
 
# 双击事件,可接受elementObj
ActionChains(driver).double_click()
 
# 点击鼠标右键
ActionChains(driver).context_click()
 
# 点击某个元素不松开,接收elementObj
ActionChains(driver).click_and_hold()
 
# # 某个元素上松开鼠标左键,接收elementObj
ActionChains(driver).release()
posted @ 2018-01-24 23:54  尘世风  阅读(6994)  评论(0编辑  收藏  举报
*/