Selenium成长之路-13鼠标事件

日常生活中,鼠标是我们每天工作必不可少的一个设备,那么在自动化测试中,模仿鼠标操作,也是必不可少的一个功能。

那么在测试工作中,鼠标都有哪些操作呢?单机,右击,双击,拖动等,对的,平时这些操作,在自动化测试中,也是必须要用到的。

那么我们就来看看在这篇文章中,都有哪些ActionChains类:

  .click()   单机

  .context_click() 右击

  .double_click() 双击

  .drag_and_drop() 拖拽

  .move_to_elemet() 鼠标悬停

  .click_and_hold()按下鼠标左键在一个元素上

 

一、鼠标右键(right_click)

    我们还是在百度首页举例子; 鼠标右击  "百度一下"按钮

代码如下:

# coding = utf-8
from selenium import  webdriver
import time
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains

driver = webdriver.Chrome()
url = 'http://www.baidu.com'
driver.get(url)

# 设定需要定位到的元素,即"百度一下"按钮
right=driver.find_element(By.XPATH,"//*[@id = 'su']")


# 增加一个判断
try:
    # 对定位到的元素进行操作
    ActionChains(driver).context_click(right).perform()  #perform()执行所有ActionChains中存储的行为
    print("test pass")

except Exception as e:
    print("test failed",format(e))


time.sleep(5)
driver.quit()

 

这里首先需要导入ActionChains类,即:from selenium.webdriver.common.action_chains import ActionChains

第二步需要定位到,需要右键的元素:即:right = driver.find_element(By.XPATH,"//*[@id ='su' ]")

第三步,右键定位到的元素,即:ActionChains(driver).context_click(right).preform()

这里需要说明的几点:

  ①ActionChains(driver):  driver 就是webdriver实例执行用户的操作,即  dirver = webdriver.Chorme()

  ②context_click(right):就是右击需要定位的元素即:right = driver.find_element(By.XPATH,"//*[@id ='su' ]")

 ③preform(): 就是执行所有ActionChains中存储的行为,同时也是ActionChains类提供的方法,一般preform()与ActionChains()配合使用。这个记住就好了

 

二、鼠标双击(double_click)

       连续双击"百度一下"按钮

代码如下:

#百度输入框输入信息
driver.find_element(By.XPATH,"//*[@id='kw']").send_keys("DJ_Carl")

# 设定需要定位到的元素,即"百度一下"按钮
double=driver.find_element(By.XPATH,"//*[@id = 'su']")

# 增加一个判断
try:
    # 对定位到的元素进行操作
    ActionChains(driver).double_click(double).perform()  #perform()执行所有ActionChains中存储的行为
    print("test pass")

except Exception as e:
    print("test failed",format(e))
...

 

三、鼠标悬停(move_to_element)

 鼠标悬停在百度首页的"设置"文字链接上

#定位需要悬浮的目标元素
setting = driver.find_element(By.XPATH,"//*/a[contains(@href,'http://www.baidu.com/gaoji/preferences.html')]")

# 使用link_text定位 "设置"文字链接
# setting =driver.find_element_by_link_text('设置')

# 增加一个判断
try:
    # 对定位到的元素进行操作
    ActionChains(driver).move_to_element(setting).perform()  #perform()执行所有ActionChains中存储的行为
    time.sleep(3)
    print("test pass")

except Exception as e:
    print("test failed",format(e))

 

这里使用两个方法,XPath() 和link_text(),如果能判定当前页面只有这一个唯一元素的话,使用link_text()也是很方便的。

以上就是ActionChains类事件的一些方法,关于ActionChains类的其他方法,有时间的话,会陆续加上的。

    

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Carl_奕然

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值