python+selenium之鼠标事件

版权声明:本文为CSDN博主「药药君」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/Static_at/article/details/81115062

鼠标事件同样需要导入包,与键盘事件的都在common下。

不过鼠标事件中,会存在一些微微的Bug,在运行的时候可能在页面实际效果会观察不到,但是代码本身是没有错误的。

以下为鼠标事件中的一些方法:

鼠标事件对应代码
鼠标右击context_click()
鼠标左击click_and_hold()
鼠标双击double_click()
鼠标拖动drag_and_drop()
悬停move_to_element()

使用perform()进行提交生效操作

使用语法:

ActionChains(网页对象名).事件(元素对象).perform()

那么同样在百度首页进行演示,请查看代码及注释:
在这里插入图片描述

#coding:utf-8
from selenium import webdriver
from time import sleep
from selenium.webdriver.common.action_chains import ActionChains #调用鼠标事件所在的包
'''
右击  context_click()
左击  click_and_hold()
双击  double_click()
拖动  drag_and_drop()
悬停  move_to_element()
使用perform()提交生效操作
使用语法:ActionChains(网页窗口对象).事件(元素对象).perform()
'''
bro = webdriver.Chrome()
bro.maximize_window()   #最大化窗口
bro.get("https://baidu.com")
#实现对着百度输入框右击:
"""
a = bro.find_element_by_id("kw")
ActionChains(bro).context_click(a).perform() 
"""
 #对着hao123双击
"""
b = bro.find_element_by_xpath("//a[text()='hao123']")  #定位到hao123
#b = bro.find_element_by_xpath("//div[@id='u_sp']/child::a[3]")  #定位到hao123
sleep(1)
ActionChains(bro).double_click(b).perform()
"""
#拖动与上述语法略有不同 格式:ActionChains(网页窗口对象).事件(元素对象1,元素对象2).perform()
# ActionChains(bro).drag_and_drop(b,a).perform()  #显示不明显,参考下面代码
c = bro.find_element_by_xpath("//a[text()='学术']")
# ActionChains(bro).move_to_element(c).perform()  #悬停在学术上
sleep(3)
bro.quit()

拖拽

格式:
格式:ActionChains(网页窗口对象).事件(元素对象1,元素对象2).perform()
示例代码:
from selenium import webdriver
import unittest
from selenium.webdriver import ActionChains
import time

url = 'http://jqueryui.com/resources/demos/draggable/scroll.html'
driver = webdriver.Chrome()
driver.get(url)
# 获取第一,二,三能拖拽的元素
drag1 = driver.find_element_by_id('draggable')
drag2 = driver.find_element_by_id('draggable2')
drag3 = driver.find_element_by_id('draggable3')

# 创建一个新的ActionChains,将webdriver实例对driver作为参数值传入,然后通过WenDriver实例执行用户动作

action_chains = ActionChains(driver)
# 将页面上的第一个能被拖拽的元素拖拽到第二个元素位置
action_chains.drag_and_drop(drag1, drag2).perform()

# 将页面上的第三个能拖拽的元素,向右下拖动10个像素,共拖动5次
for i in range(5):
    action_chains.drag_and_drop_by_offset(drag3, 10, 10).perform()
    time.sleep(2)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值