十.python+selenium之鼠标事件

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

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

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

导入鼠标事件包的方法:  from selenium.webdriver.common.action_chains import ActionChains

鼠标右击: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.Firefox()
bro.maximize_window()
bro.get("https://baidu.com")
a = bro.find_element_by_id("kw")
# ActionChains(bro).context_click(a).perform() #对着百度输入框右击
b = bro.find_element_by_xpath(".//*[@id='u1']/a[2]")
sleep(1)
ActionChains(bro).double_click(b).perform() #对着hao123双击
#拖动与上述语法略有不同 格式:ActionChains(网页窗口对象).事件(元素对象1,元素对象2).perform()
# ActionChains(bro).drag_and_drop(b,a).perform()
c = bro.find_element_by_xpath(".//*[@id='u1']/a[8]")
# ActionChains(bro).move_to_element(c).perform()  #悬停在设置上
sleep(3)
bro.quit()

猜你喜欢

转载自blog.csdn.net/Static_at/article/details/81115062
今日推荐