ActionChains
In the process of UI automation testing, we often encounter the kind of scene where the elements appear only after the mouse is hovered, and then we have to simulate the mouse hovering to a certain position and do a series of coherent operations. Selenium gives We provide the ActionChains module.
introduction method
1
|
from selenium.webdriver.common.action_chains import ActionChains
|
In fact, the core idea of the implementation of the ActionChains module is that when you call the ActionChains method, it will not be executed immediately, but will store all operations in a List in order. When you call the perform() method, the queue The times in are executed sequentially. (Note: A ruler tool is recommended, MeasurerIt)
drag_and_drop
1
2
3
4
5
6
7
8
|
# 将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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
# 鼠标移动到某一个元素上,结束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://ui.imdsx.cn/uitester/')
time.sleep(2)
driver.execute_script('document.body.scrollTop=0')
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
# 单击事件,可接受elementObj
ActionChains(driver).click()
# 双击事件,可接受elementObj
ActionChains(driver).double_click()
# 点击鼠标右键
ActionChains(driver).context_click()
# 点击某个元素不松开,接收elementObj
ActionChains(driver).click_and_hold()
# # 某个元素上松开鼠标左键,接收elementObj
ActionChains(driver).release()
|
key_down 与 key_up
Sometimes when we need to simulate keyboard operation, we need to use the key operation in ActionChains. Two methods are provided, key_down and key_up, to simulate pressing a key on the keyboard, and releasing a key, the received The parameters are the Keys and elementObj of the key. Can be used in conjunction with send_keys (eg: select all, copy, cut, paste)
1
2
3
|
# key_down 模拟键盘摁下某个按键 key_up 松开某个按键,与sendkey连用完成一些操作,每次down必须up一次否则将出现异常
ActionChains(driver).key_down(Keys.CONTROL,dom).send_keys('a').send_keys('c').key_up(Keys.CONTROL)\
.key_down(Keys.CONTROL,dom1).send_keys('v').key_up(Keys.CONTROL).perform()
|
Keys is actually a keyboard event module provided by Selenium. When simulating keyboard events, you need to import the Keys module
import path
1
|
from selenium.webdriver.common.keys import Keys
|