Selenium----鼠标操作

  在实际web测试中,会有很多鼠标的操作,不单单只有单击click(),有时候还要用到右击、双击、拖动等操作,
这些操作都包含在ActionChains类中。ActionChains类鼠标操作的常用方法

  • context_click()  右击
  • double_click()  双击
  • drag_and_drop()  拖动
  • move_to_element()  鼠标悬浮在一个元素上
  • click_and_hold()  按下鼠标左键在一个元素上不送开

在使用ActionChains类下面的方法之前,需要先引入ActionChains类

from selenium.webdriver.common.action_chains import ActionChains 

这里需要注意的是:ActionChains(driver),
                            driver:webdriver实例执行用户操作。
                            ActionChains用于生产用户的行为,所有的行为都存储在actionchains对象上,再通过perform()执行所有ActionChains中存储的行为。
                            perform()同样也是ActionChains类提供的方法,通常与ActionChains()配合使用。


鼠标右击context_click()操作

#定位到要右击的元素
right =driver.find_element_by_xpath("xx")

#对定位到的元素执行鼠标右键操作
ActionChains(driver).context_click(right).perform() 


鼠标双击double_click()操作

#定位到要双击的元素
double =driver.find_element_by_xpath("xxx") 

 #对定位到的元素执行鼠标双击操作 
ActionChains(driver).double_click(double).perform() 


鼠标拖放drag_and_drop()操作

#定位元素的原位置 
element = driver.find_element_by_name("xxx")

#定位元素要移动到的目标位置 
target = driver.find_element_by_name("xxx")

#执行元素的移动操作 
ActionChains(driver).drag_and_drop(element, target).perform()

鼠标悬浮在一个元素上move_to_element()

#定位鼠标需要悬浮的元素
ele= driver.find_element_by_id('i1')

#执行鼠标操作
ActionChains(driver).move_to_element(ele).perform()

猜你喜欢

转载自www.cnblogs.com/yttbk/p/11077246.html