(selenium+python)_UI自动化06_模拟鼠标事件

模拟鼠标事件

web网站常用鼠标事件为:点击(click可实现)、右击、双击、悬停、长按、拖动。在selenium中可以通过 ActionChains类实现模拟鼠标常用操作。

ActionChains类中鼠标常用方法:

1 context_click(element)  # 右击
2 double_click(element)  # 双击
3 click_and_hold(element)  # 长按
4 move_to_element(element)  # 鼠标悬停在目标元素
5 move_by_offset(xoffset, yoffset)  # 鼠标悬停在目标坐标
6 drag_and_drop(source_ele, target_ele)  # 拖动

 备注:

1,使用时需导入ActionChains:from selenium.webdriver.common.action_chains import ActionChains

2,模拟事件后需添加.perform()才会执行操作

实例

模拟鼠标悬停

 1 # 模拟鼠标悬停实例
 2 from selenium.webdriver.common.action_chains import ActionChains
 3 from selenium import webdriver
 4 from time import sleep
 5  
 6 driver = webdriver.Chrome()
 7 driver.get('https://www.jd.com/')  #打开京东
 8 sleep(3)
 9  
10 # 模拟鼠标事件
11 tag_element = driver.find_element_by_xpath('//*[text()="我的京东"]')  # 菜单-我的京东
12 ActionChains(driver).move_to_element(tag_element).perform()  # 鼠标悬浮在-我的京东,展开子菜单

猜你喜欢

转载自www.cnblogs.com/mini-monkey/p/12109691.html
今日推荐