selenium--模拟鼠标操作
一、应用场景
在UI自动化里,会有个别场景会用到鼠标悬浮,这时候只借助浏览器操作是实现不了的。需要模拟鼠标进行悬浮操作。
此时就需要用到 ActionChains- 鼠标操作类。
二、操作方法
from selenium.webdriver.common.action_chains import ActionChains
1.鼠标的动作
click_and_hold:按住等待
release: 释放
context_click: 模拟鼠标右键点击
double_click: 双击
drag_and_drop: 拖拽
key_down : 按键
move_to_element:悬浮
pause: 暂停
鼠标的常用操作可以从源码查看,这里列出的是几个简单的。
2.执行鼠标的操作 -perform()
三、代码示例
from selenium.webdriver.commom.action_chains import ActionChains
from selenium import webdriver
driver = webdriver.Chrome()
driver.get("https://www.baidu.com")
1.实例化ActionChains 对象
ac = ActionChains(driver)
2.调用鼠标操作
el = dirver.find_element_by_xpath("//span[text()='属性']")
ac.move_to_element(e1) # 操作1
ac.click() # 操作2
.... #操作3......
3.执行鼠标操作
ac.perform()
模拟鼠标操作过程中不要手动操作鼠标,不然会打断鼠标的操作。
三、常见问题
对于动态元素怎么处理
先执行某项操作让元素可见,等待之后,对元素进行操作。

浙公网安备 33010602011771号