一、鼠标事件 如,移动、点击、释放、单击、右击,拖动等

键盘事件如:输入、回车、粘贴、复制、剪贴等

使用ActionsChains类和Keys类之前都必须先导入

      from selenium.webdriver.common.action_chains import ActionChains

      from selenium.webdriver.common.keys import Keys

二、ActionsChains类的常用方法

1、move_to_element()悬停

     以百度首页为例,鼠标悬浮至“设置”上时,会出现设置下方的多个选项

代码如下:

#coding=utf-8
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
import time as t
driver=webdriver.Firefox()
driver.maximize_window()
driver.implicitly_wait(30)
driver.get('http://www.baidu.com/')
t.sleep(2)
#1.move_to_element()悬停
ele=driver.find_element_by_link_text(u"设置")
ActionChains(driver).move_to_element(ele).perform()
#点击搜索设置
driver.find_element_by_css_selector('.setpref').click()
t.sleep(2)
driver.quit()

2、右击context_click()

以百度云盘里,右击文件时上出现分享等选项为例

#coding=utf-8
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
import time as t
driver=webdriver.Firefox()
driver.maximize_window()
driver.implicitly_wait(30)
driver.get('https://pan.baidu.com/')
t.sleep(2)
driver.find_element_by_css_selector('.account-title>a').click()
driver.find_element_by_id('TANGRAM__PSP_4__username').send_keys('182918*****)
driver.find_element_by_id('TANGRAM__PSP_4__password').send_keys('XXXXXXX')
driver.find_element_by_id('TANGRAM__PSP_4__submit').click()
file=driver.find_element_by_css_selector('.hfvvQGz')
ActionChains(driver).context_click(file).click()
t.sleep(5)
driver.quit()

3、click_and_hold()按住鼠标左键在原元素上不释放

以打开百度首页,在搜索框输入Python,点击“百度一下”不释放

#coding=utf-8
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
import time as t
driver=webdriver.Firefox()
driver.maximize_window()
driver.implicitly_wait(30)
driver.get('http://www.baidu.com/')
t.sleep(2)
#2.click_and_hold()按住鼠标左键在原元素上不释放
driver.find_element_by_id('kw').send_keys('python')
sou=driver.find_element_by_id('su')
ActionChains(driver).click_and_hold(sou).perform()
#释放鼠标
ActionChains(driver).click_and_hold(sou).release()
t.sleep(2)
driver.quit() 三、键盘Keys类的常用方法

键盘事件可以实现点击F1到F12,回车,剪切等,部分例子的代码如下:

#coding=utf-8
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
import time as t
driver=webdriver.Firefox()
driver.maximize_window()
driver.implicitly_wait(30)
driver.get('http://www.savingpay.com/')
t.sleep(2)
ele=driver.find_element_by_id('searchMsg')
#键盘点击F12
#ele.send_keys(Keys.F12)
#输入文字后,键盘点击Ctrl+A全选输入的文字
ele.send_keys("java")
t.sleep(5)
ele.send_keys(Keys.CONTROL,'a')
t.sleep(5)
ele.send_keys(Keys.BACK_SPACE)
t.sleep(5)
driver.quit()

   

05-14 10:26