python+selenium自动化(鼠标事件)-18.04.10记

鼠标事件使用导入方法

from selenium .webdruver.common.action_chains import ActionChains

 一、通过指定的元素,来定位需要点击的坐标

#官方代码

def move_to_element_with_offset(self, to_element, xoffset, yoffset):

通过指定元素的偏移量移动鼠标。偏移量与元素的左上角相对

 - to_element: 定位需要悬停的元素
- xoffset: X 轴偏移量 - yoffset: Y 轴偏移量

#项目中实际代码,tw为参照的元素,239为x坐标,159为y坐标,已源元素的左上角为定位点,向右向下是正数,向上向左是负数。
ActionChains(browser).move_to_element_with_offset(tw,239,159),click().perform()


备注:连着执行多个事件的时候,就得多个对象,一个ActionChains是一个独立的对象,如果用action=ActionChains来赋值,引用action的话,就会导致是一个对象,会重复执行事件,每次遇到perform()就会把前面的事件再都执行一遍(如下边脚本,必须用ActionChains(browser))。
ActionChains(browser).move_to_element_with_offset(tw,239,159),click().perform()
ActionChains(browser).move_to_element_with_offset(tw,239,159),click().perform()
ActionChains(browser).move_to_element_with_offset(tw,239,159),click().perform()


二、drag_and_drop 拖动鼠标
分俩种,一种是按住源元素的鼠标左键,然后移动到目标坐标后释放鼠标按钮,source为源元素,代码如下
#官方代码
ActionChains(browser).drag_and_drop_by_offset(self, source, xoffset, yoffset)


#项目中实际代码
time.sleep(3)
browser.switch_to.frame("myframe")#有frame框的,要跳进frame框里来
shu = browser.find_element_by_id("gameCanvas")#定位被拖拽的源元素
ActionChains(browser).drag_and_drop_by_offset(shu, 0 ,200).perform() # 0是横向移动 200那个是竖着移动
browser.switch_to_default_content()#退出frame框






 
posted @ 2018-04-10 10:29  zwhnh  阅读(57)  评论(0)    收藏  举报